Heap Sort

• 05-18-2005
silicon
Heap Sort
Hi everyone I am having a little problem with a heap sort code that I am writing. I have found a few templates that all looked the same but am having problems writing it on my own because I do not understand them completely. I completely understand how the heap sort algorithm works in theory and can draw out what happens using a binary tree. When implemented in code however I do not understand certain declarations like (root*2). I just wish I had a better picture of it. Please let me know if anyone can explain this or can direct me to a book or website that has an explanation of it.

Thanks

Code:

```void heapSort(int numbers[], int array_size) {   int i, temp;   for (i = (array_size / 2)-1; i >= 0; i--)     siftDown(numbers, i, array_size);   for (i = array_size-1; i >= 1; i--)   {     temp = numbers[0];     numbers[0] = numbers[i];     numbers[i] = temp;     siftDown(numbers, 0, i-1);   } } void siftDown(int numbers[], int root, int bottom) {   int done, maxChild, temp;   done = 0;   while ((root*2 <= bottom) && (!done))   {     if (root*2 == bottom)       maxChild = root * 2;     else if (numbers[root * 2] > numbers[root * 2 + 1])       maxChild = root * 2;     else       maxChild = root * 2 + 1;     if (numbers[root] < numbers[maxChild])     {       temp = numbers[root];       numbers[root] = numbers[maxChild];       numbers[maxChild] = temp;       root = maxChild;     }     else       done = 1;   } }```
• 05-18-2005
Stoned_Coder
no time to explain now so just look over this applet