Skip to content

Commit 17113fc

Browse files
committed
add HeapSort
0 parents  commit 17113fc

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

HeapSort.php

+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
<?php
2+
3+
$array = [81,138,4,9,7,81,1,3,8,48,36,84,315,87,9,844,311,3,4,89,69,8944];
4+
5+
function heapSort(array $array)
6+
{
7+
8+
$t1 = microtime(true);
9+
10+
//php script here
11+
for($i = count($array) - 1; $i > 0; $i--)
12+
{
13+
for($j = $i; $j > 0; $j--)
14+
{
15+
heapAdjust($array, $j);
16+
}
17+
swap($array, $i, 0);
18+
}
19+
print_r($array);
20+
21+
$t2 = microtime(true);
22+
echo (($t2-$t1)*1000).'ms';
23+
}
24+
25+
function heapAdjust(array &$array, $j)
26+
{
27+
if ($array[$j] > $array[floor($j/2)])
28+
{
29+
swap($array, $j, floor($j/2));
30+
}
31+
}
32+
33+
function swap(array &$array, $i, $j)
34+
{
35+
$temp = $array[$i];
36+
$array[$i] = $array[$j];
37+
$array[$j] = $temp;
38+
}
39+
40+
heapSort($array);
41+
42+
?>

0 commit comments

Comments
 (0)