Skip to content

Commit 145dce3

Browse files
Added Counting Sort Algorithm
1 parent 0b6e77b commit 145dce3

File tree

2 files changed

+59
-2
lines changed

2 files changed

+59
-2
lines changed

README.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -2923,8 +2923,8 @@ In order to achieve greater coverage and encourage more people to contribute to
29232923
</a>
29242924
</td>
29252925
<td> <!-- Java -->
2926-
<a href="./CONTRIBUTING.md">
2927-
<img align="center" height="25" src="./logos/github.svg" />
2926+
<a href="./src/java/CountingSort.java">
2927+
<img align="center" height="25" src="./logos/java.svg" />
29282928
</a>
29292929
</td>
29302930
<td> <!-- Python -->

src/java/CountingSort.java

+57
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
public class CountingSort {
2+
3+
int getMax(int[] a, int n) {
4+
int max = a[0];
5+
for (int i = 1; i < n; i++) {
6+
if (a[i] > max)
7+
max = a[i];
8+
}
9+
return max;
10+
}
11+
12+
void countSort(int[] a, int n) {
13+
int[] output = new int[n + 1];
14+
int max = getMax(a, n);
15+
// int max = 42;
16+
int[] count = new int[max + 1];
17+
18+
for (int i = 0; i <= max; ++i) {
19+
count[i] = 0;
20+
}
21+
22+
for (int i = 0; i < n; i++) {
23+
count[a[i]]++;
24+
}
25+
26+
for (int i = 1; i <= max; i++)
27+
count[i] += count[i - 1];
28+
29+
for (int i = n - 1; i >= 0; i--) {
30+
output[count[a[i]] - 1] = a[i];
31+
count[a[i]]--;
32+
}
33+
34+
for (int i = 0; i < n; i++) {
35+
a[i] = output[i];
36+
}
37+
}
38+
39+
/* Function to print the array elements */
40+
void printArray(int a[], int n) {
41+
int i;
42+
for (i = 0; i < n; i++)
43+
System.out.print(a[i] + " ");
44+
}
45+
46+
public static void main(String args[]) {
47+
int a[] = { 11, 30, 24, 7, 31, 16, 39, 41 };
48+
int n = a.length;
49+
CountingSort c1 = new CountingSort();
50+
System.out.println("\nBefore sorting array elements are - ");
51+
c1.printArray(a, n);
52+
c1.countSort(a, n);
53+
System.out.println("\nAfter sorting array elements are - ");
54+
c1.printArray(a, n);
55+
System.out.println();
56+
}
57+
}

0 commit comments

Comments
 (0)