Heap Sort
Heap sort is a comparison based sorting algorithm. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.
function MaxHeapify(&$data, $heapSize, $index) {
$left = ($index + 1) * 2 - 1;
$right = ($index + 1) * 2;
$largest = 0;
if ($left < $heapSize && $data[$left] > $data[$index])
$largest = $left;
else
$largest = $index;
if ($right < $heapSize && $data[$right] > $data[$largest])
$largest = $right;
if ($largest != $index)
{
$temp = $data[$index];
$data[$index] = $data[$largest];
$data[$largest] = $temp;
MaxHeapify($data, $heapSize, $largest);
}
}
function HeapSort(&$data, $count) {
$heapSize = $count;
for ($p = ($heapSize - 1) / 2; $p >= 0; $p--)
MaxHeapify($data, $heapSize, $p);
for ($i = $count - 1; $i > 0; $i--)
{
$temp = $data[$i];
$data[$i] = $data[0];
$data[0] = $temp;
$heapSize--;
MaxHeapify($data, $heapSize, 0);
}
}
Example
$data = array(-1, 25, -58964, 8547, -119, 0, 78596);
HeapSort($data, 7);
Output
-58964
-119
-1
0
25
8547
78596