A heap is a tree-based data structure in which all the nodes of the tree are in a specific order.For example, if is the parent node of , then the value of follows a specific order with respect to the value of and the same order will be followed across the tree.
Posted by: Guest
on June-02-2020
3
heap
void max_heapify (int Arr[ ], int i, int N)
{
int left =2*i //left childint right =2*i +1//right childif(left<= N and Arr[left] > Arr[i] )
largest = left;
else
largest = i;
if(right <= N and Arr[right] > Arr[largest] )
largest = right;
if(largest != i )
{
swap (Arr[i] , Arr[largest]);
max_heapify (Arr, largest,N);
}
}
Implementation of heap sort in C++:
#include <bits/stdc++.h>
using namespacestd;
// To heapify a subtree rooted with node i which is// Heapify:- A process which helps regaining heap properties in tree after removal voidheapify(int A[], int n, int i)
{
int largest = i; // Initialize largest as rootint left_child =2* i +1; // left = 2*i + 1int right_child =2* i +2; // right = 2*i + 2// If left child is larger than rootif (left_child < n && A[left_child] > A[largest])
largest = left_child;
// If right child is larger than largest so farif (right_child < n && A[right_child] > A[largest])
largest = right_child;
// If largest is not rootif (largest != i) {
swap(A[i], A[largest]);
// Recursively heapify the affected sub-treeheapify(A, n, largest);
}
}
// main function to do heap sortvoidheap_sort(int A[], int n)
{
// Build heap (rearrange array)for (int i = n / 2-1; i >=0; i--)
heapify(A, n, i);
// One by one extract an element from heapfor (int i = n -1; i >=0; i--) {
// Move current root to endswap(A[0], A[i]);
// call max heapify on the reduced heapheapify(A, i, 0);
}
}
/* A function to print sorted Array */voidprintArray(int A[], int n)
{
for (int i =0; i < n; ++i)
cout << A[i] <<" ";
cout <<"\n";
}
// Driver programintmain()
{
int A[] = { 22, 19, 3, 25, 26, 7 }; // array to be sortedint n =sizeof(A) / sizeof(A[0]); // n is size of arrayheap_sort(A, n);
cout <<"Sorted array is \n";
printArray(A, n);
}
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems
resetting your password contact us
Check Your Email and Click on the link sent to your email