forked from sandersyao/PHP-Data-Structure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuick.class.php
More file actions
70 lines (52 loc) · 1.76 KB
/
Copy pathQuick.class.php
File metadata and controls
70 lines (52 loc) · 1.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<?php
/**
* 快速排序 (分区交换排序)
*/
class Sort_Quick {
/**
* 执行
*/
static public function exec (Sort_SRC $src, $compare = NULL) {
$compare = is_callable($compare) ? $compare : array(__CLASS__, 'compareDefault');
self::_partition($src, $compare);
}
/**
* 分区交换
*
* @param Sort_SRC $src 排序源
* @param callback $compare 比较逻辑
* @param int $offsetStart 起始位置
* @param int $offsetEnd 结束位置
*/
static private function _partition (Sort_SRC $src, $compare, $offsetStart = 0, $offsetEnd = NULL) {
$offsetEnd = NULL === $offsetEnd ? count($src) - 1 : $offsetEnd;
if ($offsetEnd <= $offsetStart) {
return ;
}
$offsetPivot = mt_rand($offsetStart, $offsetEnd);
$pivot = $src[$offsetPivot];
$src->swap($offsetStart, $offsetPivot);
for ($offset = $offsetStore = $offsetStart + 1; $offset <= $offsetEnd; $offset ++) {
$result = call_user_func($compare, $src[$offset], $pivot);
if ($result >= 0) {
$src->swap($offset, $offsetStore);
++ $offsetStore;
}
}
$src->swap($offsetStart, $offsetStore - 1);
self::_partition($src, $compare, $offsetStart, $offsetStore - 2);
self::_partition($src, $compare, $offsetStore, $offsetEnd);
}
/**
* 默认比较逻辑
*
* @param mixed $a 源
* @param mixed $b 排序判断方法
*/
public static function compareDefault ($a, $b) {
if ($a == $b) {
return 0;
}
return $a < $b ? 1 : -1;
}
}