File tree Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Expand file tree Collapse file tree 2 files changed +37
-1
lines changed Original file line number Diff line number Diff line change 34
34
- Merge Sort
35
35
- Quick Sort
36
36
- Bucket Sort
37
- - Counting Sort
37
+ - [ Counting Sort] ( ./Sorting/Counting%20Sort )
38
38
- Heap Sort
39
39
- Radix Sort
40
40
Original file line number Diff line number Diff line change
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
+ ?>
You can’t perform that action at this time.
0 commit comments