Skip to content

Commit a4c63d6

Browse files
authored
Merge pull request darpanjbora#108 from shanvijha30/algorithm
Added Counting Sort Algorithm
2 parents 9b09097 + 06e2947 commit a4c63d6

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Sorting Algorithms/CountingSort.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import java.util.Arrays;
2+
3+
class CountingSort {
4+
void countSort(int array[], int size) {
5+
int[] output = new int[size + 1];
6+
7+
// Find the largest element of the array
8+
int max = array[0];
9+
for (int i = 1; i < size; i++) {
10+
if (array[i] > max)
11+
max = array[i];
12+
}
13+
int[] count = new int[max + 1];
14+
15+
// Initialize count array with all zeros.
16+
for (int i = 0; i < max; ++i) {
17+
count[i] = 0;
18+
}
19+
20+
// Store the count of each element
21+
for (int i = 0; i < size; i++) {
22+
count[array[i]]++;
23+
}
24+
25+
// Store the cummulative count of each array
26+
for (int i = 1; i <= max; i++) {
27+
count[i] += count[i - 1];
28+
}
29+
30+
// Find the index of each element of the original array in count array, and
31+
// place the elements in output array
32+
for (int i = size - 1; i >= 0; i--) {
33+
output[count[array[i]] - 1] = array[i];
34+
count[array[i]]--;
35+
}
36+
37+
// Copy the sorted elements into original array
38+
for (int i = 0; i < size; i++) {
39+
array[i] = output[i];
40+
}
41+
}
42+
43+
// Driver code
44+
public static void main(String args[]) {
45+
int[] data = { 2, 1, 2, 3, 1, 2, 4 };
46+
int size = data.length;
47+
CountingSort cs = new CountingSort();
48+
cs.countSort(data, size);
49+
System.out.println("Sorted Array in Ascending Order: ");
50+
System.out.println(Arrays.toString(data));
51+
}
52+
}

0 commit comments

Comments
 (0)