Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void siftDown(int *arr, int root, int bottom)
- {
- int maxChild; // индекс максимального потомка
- int done = 0; // флаг того, что куча сформирована
- // пока не дошли до последнего ряда
- while ((root * 2 <= bottom) && (!done))
- {
- if (root * 2 == bottom) // если мы в последнем ряду,
- maxChild = root * 2; // запоминаем левый потомок
- // иначе запоминаем больший потомок из двух
- else if (arr[root * 2] > arr[root * 2 + 1])
- maxChild = root * 2;
- else
- maxChild = root * 2 + 1;
- // если элемент вершины меньше максимального потомка
- if (arr[root] < arr[maxChild])
- {
- int temp = arr[root]; // меняем их местами
- arr[root] = arr[maxChild];
- arr[maxChild] = temp;
- root = maxChild;
- }
- else
- done = 1; // пирамида сформирована
- }
- }
- int* heapsort(int* a, size_t len)
- {
- // копируем массив - будем сортировать его копию
- int* arr = copy_array(a, len);
- // формируем нижний ряд пирамиды
- for (int i = (len / 2) - 1; i >= 0; i--)
- {
- siftDown(arr, i, len - 1);
- }
- // просеиваем через пирамиду остальные элементы
- for (int i = len - 1; i >= 1; i--)
- {
- int temp = arr[0];
- arr[0] = arr[i];
- arr[i] = temp;
- siftDown(arr, 0, i - 1);
- }
- return arr;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement