Responsive Ads Here

Saturday, 13 May 2017

Heap sort using max heap(only funtcion)

problem id:-http://practice.geeksforgeeks.org/problems/heap-sort/1

code:-

/* Main function to do heap sort. This function uses buildHeap()
   and heapify()
void heapSort(int arr[], int n)  {
    buildHeap(arr, n);
    for (int i=n-1; i>=0; i--)  {
        swap(arr[0], arr[i]);
        heapify(arr, i, 0);
    }
} */
// The functions should be written in a way that array become sorted
// in increasing order when above heapSort() is called.
// To heapify a subtree rooted with node i which is  an index in arr[].
// n is size of heap. This function  is used in above heapSor()
void heapify(int arr[], int n, int i)
{
--n;
int j=1,index;
while(j<=n)
{
index=j;
if(j+1<=n)
index=(arr[j]>arr[j+1])?j:j+1;
if(arr[(j-1)/2]<arr[index])
swap(arr[(j-1)/2],arr[index]);
j=2*index+1;
}
}

// Rearranges input array so that it becomes a min heap
void buildHeap(int arr[], int n)
{
for(int i=1;i<n;++i)
    {
    int j=i;
while(j>0 && arr[j]>arr[(j-1)/2])
swap(arr[j],arr[(j-1)/2]),j=(j-1)/2;
    }
}

No comments:

Post a Comment