1
1
<?php
2
- function _qsort ( SplFixedArray $ arr , int $ l , int $ r , callable $ compare ) {
3
- $ i = $ l ;
4
- $ j = $ r ;
5
- $ x = $ arr [( int )(( $ i + $ j ) / 2 )] ;
6
- $ t = null ;
7
- do {
8
- while ( $ compare ( $ arr [ $ i ], $ x ))
9
- ++ $ i ;
10
- while ($ compare ( $ x , $ arr [$ j ]))
11
- -- $ j ;
12
- if ( $ i <= $ j ) {
13
- $ t = $ arr [ $ i ] ;
14
- $ arr [ $ i ] = $ arr [$ j ] ;
15
- $ arr [ $ j ] = $ t ;
16
- ++ $ i ;
17
- -- $ j ;
2
+ function _qsort_partition ( \ SplFixedArray $ arr , int $ bottom , int $ top , callable $ compare_func ): int {
3
+ $ m = $ arr [( int )(( $ bottom + $ top ) / 2 )] ;
4
+ $ l = $ bottom - 1 ;
5
+ $ r = $ top + 1 ;
6
+
7
+ while ( true ) {
8
+ do {
9
+ $ l ++ ;
10
+ } while ($ l <= $ top && $ compare_func ( $ arr [$ l ], $ m ));
11
+
12
+ do {
13
+ $ r -- ;
14
+ } while ( $ r >= $ bottom && $ compare_func ( $ m , $ arr [$ r ])) ;
15
+
16
+ if ( $ l >= $ r ) {
17
+ return $ r ;
18
18
}
19
- } while ($ i <= $ j );
20
- unset($ t );
21
- unset($ x );
22
- if ($ i < $ r ) {
23
- _qsort ($ arr , $ i , $ r , $ compare );
19
+
20
+ $ tmp = $ arr [$ r ];
21
+ $ arr [$ r ] = $ arr [$ l ];
22
+ $ arr [$ l ] = $ tmp ;
24
23
}
25
- if ($ l < $ j ) {
26
- _qsort ($ arr , $ l , $ j , $ compare );
24
+ }
25
+
26
+ function _qsort (\SplFixedArray $ arr , int $ bottom , int $ top , callable $ compare_func ): void {
27
+ if ($ bottom < $ top ) {
28
+ $ j = _qsort_partition ($ arr , $ bottom , $ top , $ compare_func );
29
+ _qsort ($ arr , $ bottom , $ j , $ compare_func );
30
+ _qsort ($ arr , $ j + 1 , $ top , $ compare_func );
27
31
}
28
32
}
29
- ;
33
+
30
34
/**
31
- * 快排,默认从小到达排序 。注意:会去掉数组的键值。能用sort等函数的话就不要调用本函数
35
+ * 快排,默认从小到大排序 。注意:会去掉数组的键值。能用sort等函数的话就不要调用本函数
32
36
*
33
37
* @param array|SplFixedArray $arr
34
38
* @param callable $compare_func
@@ -63,4 +67,4 @@ function qsort(&$arr, ?callable $compare_func = null, bool $need_spl_fixed_array
63
67
$ arr = $ array ->toArray ();
64
68
}
65
69
return $ length ;
66
- }
70
+ }
0 commit comments