Heap sort algorithm

  1. /*
  2.  * C Program to sort an array based on heap sort algorithm(MAX heap)
  3.  */ 
  4. #include <stdio.h>
  5.  
  6. void main()
  7. {
  8.     int heap[10], no, i, j, c, root, temp;
  9.  
  10.     printf("\n Enter no of elements :");
  11.     scanf("%d", &no);
  12.     printf("\n Enter the nos : ");
  13.     for (i = 0; i < no; i++)
  14.        scanf("%d", &heap[i]);
  15.     for (i = 1; i < no; i++)
  16.     {
  17.         c = i;
  18.         do
  19.         {
  20.             root = (c - 1) / 2;             
  21.             if (heap[root] < heap[c])   /* to create MAX heap array */
  22.             {
  23.                 temp = heap[root];
  24.                 heap[root] = heap[c];
  25.                 heap[c] = temp;
  26.             }
  27.             c = root;
  28.         } while (c != 0);
  29.     }
  30.  
  31.     printf("Heap array : ");
  32.     for (i = 0; i < no; i++)
  33.         printf("%d\t ", heap[i]);
  34.     for (j = no - 1; j >= 0; j--)
  35.     {
  36.         temp = heap[0];
  37.         heap[0] = heap[j    /* swap max element with rightmost leaf element */
  38.         heap[j] = temp;
  39.         root = 0;
  40.         do 
  41.         {
  42.             c = 2 * root + 1;    /* left node of root element */
  43.             if ((heap[c] < heap[c + 1]) && c < j-1)
  44.                 c++;
  45.             if (heap[root]<heap[c] && c<j)    /* again rearrange to max heap array */
  46.             {
  47.                 temp = heap[root];
  48.                 heap[root] = heap[c];
  49.                 heap[c] = temp;
  50.             }
  51.             root = c;
  52.         } while (c < j);
  53.     } 
  54.     printf("\n The sorted array is : ");
  55.     for (i = 0; i < no; i++)
  56.        printf("\t %d", heap[i]);
  57.     printf("\n Complexity : \n Best case = Avg case = Worst case = O(n logn) \n");
  58. }

Comments

Popular Posts