1
|
|
|
<?php |
2
|
|
|
/** |
3
|
|
|
* Bootstrapping functions, essential and needed for Anax to work together with some common helpers. |
4
|
|
|
* |
5
|
|
|
*/ |
6
|
|
|
|
7
|
|
|
|
8
|
|
|
|
9
|
|
|
/** |
10
|
|
|
* Utility for debugging. |
11
|
|
|
* |
12
|
|
|
* @param mixed $array values to print out |
13
|
|
|
* |
14
|
|
|
* @return void |
15
|
|
|
*/ |
16
|
|
|
function dump($array) |
17
|
|
|
{ |
18
|
|
|
echo "<pre>" . htmlentities(print_r($array, 1)) . "</pre>"; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
|
22
|
|
|
|
23
|
|
|
/** |
24
|
|
|
* Sort array but maintain index when compared items are equal. |
25
|
|
|
* http://www.php.net/manual/en/function.usort.php#38827 |
26
|
|
|
* |
27
|
|
|
* @param array &$array input array |
28
|
|
|
* @param callable $cmp_function custom function to compare values |
29
|
|
|
* |
30
|
|
|
* @return void |
31
|
|
|
* |
32
|
|
|
*/ |
33
|
|
|
function mergesort(&$array, $cmp_function) |
34
|
|
|
{ |
35
|
|
|
// Arrays of size < 2 require no action. |
36
|
|
|
if (count($array) < 2) return; |
37
|
|
|
// Split the array in half |
38
|
|
|
$halfway = count($array) / 2; |
39
|
|
|
$array1 = array_slice($array, 0, $halfway); |
40
|
|
|
$array2 = array_slice($array, $halfway); |
41
|
|
|
// Recurse to sort the two halves |
42
|
|
|
mergesort($array1, $cmp_function); |
43
|
|
|
mergesort($array2, $cmp_function); |
44
|
|
|
// If all of $array1 is <= all of $array2, just append them. |
45
|
|
|
if (call_user_func($cmp_function, end($array1), $array2[0]) < 1) { |
46
|
|
|
$array = array_merge($array1, $array2); |
47
|
|
|
return; |
48
|
|
|
} |
49
|
|
|
// Merge the two sorted arrays into a single sorted array |
50
|
|
|
$array = array(); |
51
|
|
|
$ptr1 = $ptr2 = 0; |
52
|
|
|
while ($ptr1 < count($array1) && $ptr2 < count($array2)) { |
53
|
|
|
if (call_user_func($cmp_function, $array1[$ptr1], $array2[$ptr2]) < 1) { |
54
|
|
|
$array[] = $array1[$ptr1++]; |
55
|
|
|
} else { |
56
|
|
|
$array[] = $array2[$ptr2++]; |
57
|
|
|
} |
58
|
|
|
} |
59
|
|
|
// Merge the remainder |
60
|
|
|
while ($ptr1 < count($array1)) $array[] = $array1[$ptr1++]; |
61
|
|
|
while ($ptr2 < count($array2)) $array[] = $array2[$ptr2++]; |
62
|
|
|
return; |
63
|
|
|
} |
64
|
|
|
|