Skip to content

Commit 484df77

Browse files
committed
Counting sort code added
1 parent f05eb7f commit 484df77

File tree

2 files changed

+37
-1
lines changed

2 files changed

+37
-1
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,7 +34,7 @@
3434
- Merge Sort
3535
- Quick Sort
3636
- Bucket Sort
37-
- Counting Sort
37+
- [Counting Sort](./Sorting/Counting%20Sort)
3838
- Heap Sort
3939
- Radix Sort
4040

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
<?php
2+
/* Counting Sort implementation in PHP */
3+
function countingSort(Array $arr) {
4+
$count = array();
5+
6+
foreach ($arr as $item) {
7+
$count[$item] = isset($count[$item]) ? ($count[$item] + 1) : 1; //Increase the counter if exists or initialize with '1'
8+
}
9+
10+
$sortedArray = array();
11+
$minVal = min($arr); // If the min value of the array given, this line can be removed
12+
$maxVal = max($arr); //If the max value of the array given, this line can be removed
13+
14+
for ($i = $minVal; $i <= $maxVal; $i++) { //based on the frequency, building the new sorted array
15+
if(isset($count[$i])) {
16+
while ($count[$i]-- > 0) {
17+
$sortedArray[] = $i;
18+
}
19+
}
20+
}
21+
22+
return $sortedArray;
23+
}
24+
25+
/************ Testing Binary Search Implementation ***************/
26+
$testList = array();
27+
28+
foreach (range(1, 10) as $key) {
29+
$testList[] = mt_rand(-100, 100);
30+
}
31+
32+
$testList = countingSort($testList);
33+
34+
print_r($testList);
35+
36+
?>

0 commit comments

Comments
 (0)