2 Dec 2019

  • December 02, 2019
  • Amitraj
Heap Sort

-> In heap sort, heap removes the largest element from the end of partially sorted array. Reconstruct the heap after removing largest element & again remove the largest element from remaining elements and place it at the end of partially sorted array. This process is repeated until no element is left in the heap.



/* C program to sort an Array based on heap sort Algorithm (max heap) */


#include <stdio.h>
 int main()
{
    int heap[10], no, i, j, c, root, temp;
   printf("\n Enter no of elements :");
    scanf("%d", &no);
    printf("\n Enter the nos : ");
    for (i = 0; i < no; i++)
       scanf("%d", &heap[i]);
    for (i = 1; i < no; i++)
    {
        c = i;
        do
        {
            root = (c - 1) / 2;             
            if (heap[root] < heap[c])   /* to create MAX heap array */
            {
                temp = heap[root];
                heap[root] = heap[c];
                heap[c] = temp;
            }
            c = root;
        } while (c != 0);
    }
 for (j = no - 1; j >= 0; j--)
    {
        temp = heap[0];
        heap[0] = heap[j];    /* swap max element with rightmost leaf element */
        heap[j] = temp;
        root = 0;
        do
        {
            c = 2 * root + 1;    /* left node of root element */
            if ((heap[c] < heap[c + 1]) && c < j-1)
                c++;
            if (heap[root]<heap[c] && c<j)    /* again rearrange to max heap array */
            {
                temp = heap[root];
                heap[root] = heap[c];
                heap[c] = temp;
            }
            root = c;
        } while (c < j);
    } 
    printf("\n The sorted array is : ");
    for (i = 0; i < no; i++)
       printf("\t %d", heap[i]);
 return 0;
}


OUTPUT:


 Enter no of elements :5

 Enter the nos : 5  6  2  1  3

 The sorted array is :   1       2       3       5       6

Translate

Popular Posts