# PHP: Basic Programming Heap Sort algorithm

Exercise from W3schools

Write a PHP program to sort a list of elements using Heap sort.
In computer science, heapsort (invented by J. W. J. Williams in 1964) is a comparison-based sorting algorithm. Heapsort can be thought of as an improved selection sort: like that algorithm, it divides its input into a sorted and an unsorted region, and it interactively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. The improvement consists of the use of a heap data structure rather than a linear-time search to find the maximum. Although somewhat slower in practice on most machines than a well-implemented quicksort, it has the advantage of a more favorable worst-case O(n log n) runtime. Heapsort is an in-place algorithm, but it is not a stable sort.

```<?php
\$numbers = array(4,5,6,7,4,3,4,5,6,7,8,9,87,65,43,23,12,34);

var_dump(heapsort(\$numbers));

function heapsort(\$numbers){
\$sorted = array();
\$big=0;
\$pos=0;
\$length = count(\$numbers);
for (\$i=0; \$i < \$length; \$i++) {
foreach (\$numbers as \$key => \$value) {

if (\$big<\$value) {
\$big=\$value;
\$pos=\$key;

}

}
array_push(\$sorted,\$big);
array_splice(\$numbers,\$pos,1);
\$big=0;
\$pos=0;
} return \$sorted;
}

?>```

```/var/www/html/heapsort.php:4:
array (size=18)
0 => int 87
1 => int 65
2 => int 43
3 => int 34
4 => int 23
5 => int 12
6 => int 9
7 => int 8
8 => int 7
9 => int 7
10 => int 6
11 => int 6
12 => int 5
13 => int 5
14 => int 4
15 => int 4
16 => int 4
17 => int 3```