@@ -20,7 +20,58 @@ public static void main(String[] args) {
2020 performCountingSort (valuesToBeSorted );
2121 }
2222
23- private static void performCountingSort (int [] values ) {
23+ /**
24+ * Counting sort is a sorting technique based on keys between a specific range.
25+ * It works by counting the number of objects having distinct key values (kind of hashing).
26+ * Then doing some arithmetic to calculate the position of each object in the output sequence.
27+ * <p>Notes:
28+ * 1. Counting sort is efficient if the range of input data is not significantly greater than the number of objects to be sorted.
29+ * Consider the situation where the input sequence is between range 1 to 10K and the data is 10, 5, 10K, 5K.
30+ 2. It is not a comparison based sorting. It running time complexity is O(n) with space proportional to the range of data.
31+ 3. It is often used as a sub-routine to another sorting algorithm like radix sort.
32+ 4. Counting sort uses a partial hashing to count the occurrence of the data object in O(1).
33+ 5. Counting sort can be extended to work for negative inputs also.
34+ 6. This type of integer sorting algorithms are usually designed to work in either the pointer machine or random access machine models of computing
35+ </p>
36+ */
37+ private static void performCountingSort (int [] values ) {
38+
39+
40+ int n = values .length ;
41+
42+ // The output character array that will have sorted arr
43+ int output [] = new int [n ];
44+
45+ // Create a count array to store count of inidividul
46+ // characters and initialize count array as 0
47+ int count [] = new int [256 ];
48+ for (int i =0 ; i <256 ; ++i )
49+ count [i ] = 0 ;
50+
51+ // store count of each character
52+ for (int i =0 ; i <n ; ++i )
53+ ++count [values [i ]];
54+
55+ // Change count[i] so that count[i] now contains actual
56+ // position of this character in output array
57+ for (int i =1 ; i <=255 ; ++i )
58+ count [i ] += count [i -1 ];
59+
60+ // Build the output character array
61+ for (int i = 0 ; i <n ; ++i )
62+ {
63+ output [count [values [i ]]-1 ] = values [i ];
64+ --count [values [i ]];
65+ }
66+
67+ // Copy the output array to arr, so that arr now
68+ // contains sorted characters
69+ for (int i = 0 ; i <n ; ++i )
70+ values [i ] = output [i ];
71+
72+ System .out .print ("Sorted array is " );
73+ for (int i =0 ; i <values .length ; ++i )
74+ System .out .print (values [i ]+"," );
2475
2576 }
2677
0 commit comments