File tree Expand file tree Collapse file tree 1 file changed +35
-0
lines changed
leetcode/heap-sort/sort-an-array Expand file tree Collapse file tree 1 file changed +35
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments