Skip to content

Commit 8e5d871

Browse files
authored
Fix quick sort
1 parent 982308e commit 8e5d871

File tree

1 file changed

+30
-26
lines changed

1 file changed

+30
-26
lines changed

src/Sort.php

+30-26
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,38 @@
11
<?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;
1818
}
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;
2423
}
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);
2731
}
2832
}
29-
;
33+
3034
/**
31-
* 快排,默认从小到达排序。注意:会去掉数组的键值。能用sort等函数的话就不要调用本函数
35+
* 快排,默认从小到大排序。注意:会去掉数组的键值。能用sort等函数的话就不要调用本函数
3236
*
3337
* @param array|SplFixedArray $arr
3438
* @param callable $compare_func
@@ -63,4 +67,4 @@ function qsort(&$arr, ?callable $compare_func = null, bool $need_spl_fixed_array
6367
$arr = $array->toArray();
6468
}
6569
return $length;
66-
}
70+
}

0 commit comments

Comments
 (0)