Heap sort Sift Down - C Data Structure

C examples for Data Structure:Sort

Description

Heap sort Sift Down

Demo Code

#include <stdio.h>

int main() {/*from w w  w . j a  v a2  s. co  m*/
   void heapSort(int[], int);
   int num[] = {10, 327, 235, 443, 565, 648, 784, 873, 918, 719, 256, 369, 432};
   int n = 12;
   heapSort(num, n);
   for (int h = 1; h <= n; h++) 
      printf("%d ", num[h]);
   printf("\n");
}

void siftDown(int key, int num[], int root, int last) {
   int bigger = 2 * root;
   while (bigger <= last) { //while there is at least one child
      if (bigger < last) //there is a right child as well; find the bigger
         if (num[bigger+1] > num[bigger]) 
            bigger++;
      //'bigger' holds the index of the bigger child
      if (key >= num[bigger]) 
          break;

      num[root] = num[bigger];
      root = bigger;
      bigger = 2 * root;
   }
   num[root] = key;
}

void heapSort(int num[], int n) {
   void siftDown(int, int[], int, int);

   for (int h = n / 2; h >= 1; h--) 
      siftDown(num[h], num, h, n);

   for (int k = n; k > 1; k--) {
      int item = num[k]; //extract current last item
      num[k] = num[1];   //move top of heap to current last node
      siftDown(item, num, 1, k-1); //restore heap properties from 1 to k-1
   }
}

Related Tutorials