forked from SanjayDevTech/Code-with-love
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsam0hack_radixSort.php
More file actions
45 lines (45 loc) · 1.11 KB
/
Copy pathsam0hack_radixSort.php
File metadata and controls
45 lines (45 loc) · 1.11 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
<?php
function radix_sort($elements) {
// Array for 10 queues.
$queues = array(
array(), array(), array(), array(), array(), array(), array(), array(),
array(), array()
);
// Queues are allocated dynamically. In first iteration longest digits
// element also determined.
$longest = 0;
foreach ($elements as $el) {
if ($el > $longest) {
$longest = $el;
}
array_push($queues[$el % 10], $el);
}
// Queues are dequeued back into original elements.
$i = 0;
foreach ($queues as $key => $q) {
while (!empty($queues[$key])) {
$elements[$i++] = array_shift($queues[$key]);
}
}
// Remaining iterations are determined based on longest digits element.
$it = strlen($longest) - 1;
$d = 10;
while ($it--) {
foreach ($elements as $el) {
array_push($queues[floor($el/$d) % 10], $el);
}
$i = 0;
foreach ($queues as $key => $q) {
while (!empty($queues[$key])) {
$elements[$i++] = array_shift($queues[$key]);
}
}
$d *= 10;
}
}
// Example usage:
$a = array(170, 45, 75, 90, 802, 24, 2, 66);
print_r($a);
radix_sort($a);
print_r($a);
?>