Skip to content

Commit 8372206

Browse files
committed
Counting Sort Algo
1 parent f4641ce commit 8372206

File tree

1 file changed

+101
-0
lines changed

1 file changed

+101
-0
lines changed
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
1+
<?php
2+
3+
$randomSeq = array(5,14,3,2,23,3,40,38,3,4,41,8,18);
4+
5+
/**
6+
* Counting Sort algorithm for positve intergers
7+
* @param $rand Array
8+
* @return Array sorted array
9+
*/
10+
function countingSort(array &$rand): array{
11+
12+
// output array
13+
$output = array(count($rand));
14+
15+
/**
16+
* unsorted array size [$rand] - for [n] elements
17+
* Total size of [n] elements in the unsorted array
18+
*/
19+
$array_size = count($rand);
20+
21+
/**
22+
* find the max value in the range of [n] elements
23+
*/
24+
$max_val = max($rand);
25+
26+
/**
27+
* create counting slots - for [k] elements in range
28+
* In this instance [k] will equal the max value in
29+
* range.
30+
*/
31+
$count = array_fill(0, $max_val + 1,0);
32+
33+
/**
34+
* Count all occurances of range items within the given array
35+
* Range in this instance will be from 0 - (k + 1), with k being
36+
* the max value from the given array.
37+
*/
38+
foreach($rand as $key => $val){
39+
40+
/**
41+
* Increament value correponding to value
42+
* i.e $count[2]++
43+
*/
44+
$count[$val]++;
45+
46+
}
47+
48+
/**
49+
* Store the cummulative count of each element
50+
* Iterate count array and set start index position of
51+
* counted elements.
52+
*/
53+
for($idx = 1; $idx <= $max_val; $idx++){
54+
55+
/**
56+
* We are adding the previous index's count
57+
* to the current count. This will continue
58+
* for [k] range of elements.
59+
*/
60+
$count[$idx] = ($count[$idx] + $count[$idx - 1]);
61+
62+
}
63+
64+
// Find the index of each element
65+
for ($idx = $array_size - 1; $idx >= 0; $idx--) {
66+
67+
/**
68+
* So we use the value at the current index pointed to.
69+
* We then grap its cummulative value
70+
* and adjust to correct position, by subtracting 1.
71+
*/
72+
$index = ($count[$rand[$idx]] - 1);
73+
74+
/**
75+
* We then store the value from the original
76+
* array in the adjusted postion.
77+
*/
78+
$output[$index] = $rand[$idx];
79+
80+
/**
81+
* We then decreament the current stored value to reflect
82+
* the moved value.
83+
*/
84+
$count[$rand[$idx]]--;
85+
86+
}
87+
88+
89+
// Copy the sorted array into the original array
90+
for($idx = 0; $idx <= $array_size - 1; $idx++){
91+
92+
// move to correct position
93+
$rand[$idx] = $output[$idx];
94+
95+
}
96+
97+
return $rand;
98+
99+
}
100+
101+
print_r(countingSort($randomSeq));

0 commit comments

Comments
 (0)