forked from sandersyao/PHP-Data-Structure
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertion.class.php
More file actions
60 lines (44 loc) · 1.25 KB
/
Copy pathInsertion.class.php
File metadata and controls
60 lines (44 loc) · 1.25 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
<?php
/**
* 插入排序
*/
class Sort_Insertion {
/**
* 插入排序
*
* @param Sort_SRC $src 源
* @param callback $compare 排序判断方法
*/
public static function exec (Sort_SRC $src, $compare = NULL) {
$compare = is_callable($compare) ? $compare : array(__CLASS__, 'compareDefault');
for ($offset = 1; $offset < count($src); $offset ++) {
$target = $offset - 1;
$value = $src[$offset];
while (0 <= $target) {
$result = call_user_func($compare, $src[$target], $value);
if ($result >= 0) {
$src[$target + 1] = $value;
break;
}
$src[$target + 1] = $src[$target];
if (0 == $target) {
$src[$target] = $value;
break;
}
-- $target;
}
}
}
/**
* 默认比较逻辑
*
* @param mixed $a 源
* @param mixed $b 排序判断方法
*/
public static function compareDefault ($a, $b) {
if ($a == $b) {
return 0;
}
return $a < $b ? 1 : -1;
}
}