We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
1 parent e2aaafc commit 26b2179Copy full SHA for 26b2179
leetcode/heap-sort/sort-an-array/adaa-mgbede.php
@@ -0,0 +1,35 @@
1
+<?php
2
+
3
+/**
4
+ * @param Integer[] $nums
5
+ * @return Integer[]
6
+ */
7
+function sortArray($nums) {
8
+ $n = count($nums);
9
10
+ $heapSize = (int)($n/2) - 1;
11
12
+ for ($i = $heapSize; $i >= 0; $i--) {
13
+ maxHeap($nums, $n, $i);
14
+ }
15
16
+ for ($i = $n; $i >= 2; $i--) {
17
+ $k = $i - 1;
18
+ list($nums[$k], $nums[0]) = [$nums[0], $nums[$k]];
19
+ maxHeap($nums, $k, 0);
20
21
+ return $nums;
22
+}
23
24
+function maxHeap(&$arr, $n, $i) {
25
+ $j = $i;
26
+ $l = (2 * $i) + 1;
27
+ $r = (2 * $i) + 2;
28
+ if($l < $n && $arr[$l] > $arr[$j]) $j = $l;
29
+ if($r < $n && $arr[$r] > $arr[$j]) $j = $r;
30
31
+ if ($j != $i) {
32
+ list($arr[$j], $arr[$i]) = [$arr[$i], $arr[$j]];
33
+ maxHeap($arr, $n, $j);
34
35
0 commit comments