Skip to content

Commit 9b7e6d2

Browse files
authored
Merge pull request #333 from vijaykrishna-11/Added-CountingSort
Added Counting Sort Algorithm
2 parents 4db4b9d + 4844be1 commit 9b7e6d2

File tree

2 files changed

+56
-2
lines changed

2 files changed

+56
-2
lines changed

README.md

Lines changed: 2 additions & 2 deletions
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

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

0 commit comments

Comments
 (0)