tags:

views:

130

answers:

2

Hello,

Can someone clearly explain me how these functions of heap sort are working??

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;
  }
}
A: 

Start by googling "heapsort" and you might come up with this. If you have a more specific question, that would be more appropriate.

NickLarsen
+1  A: 

This page has ample explanations with diagrams on heap sort. It can help to think about it as a tournament: first you insert all players such that the top player is the winner. Then you extract the winner, promote a loser as new winner, and perform adjustments so that you again get a proper tournament, with the new winner being the best of the remaining players.

Then you iterate.

Thomas Pornin
thanks this was really helpfull.
Jonathan