Skip to content

Added Counting Sort Algorithm #333

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 6, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2923,8 +2923,8 @@ In order to achieve greater coverage and encourage more people to contribute to
</a>
</td>
<td> <!-- Java -->
<a href="./CONTRIBUTING.md">
<img align="center" height="25" src="./logos/github.svg" />
<a href="./src/java/CountingSort.java">
<img align="center" height="25" src="./logos/java.svg" />
</a>
</td>
<td> <!-- Python -->
Expand Down
54 changes: 54 additions & 0 deletions src/java/CountingSort.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
public class CountingSort {

int getMax(int[] a, int n) {
int max = a[0];
for (int i = 1; i < n; i++) {
if (a[i] > max) max = a[i];
}
return max;
}

void countSort(int[] a, int n) {
int[] output = new int[n + 1];
int max = getMax(a, n);
// int max = 42;
int[] count = new int[max + 1];

for (int i = 0; i <= max; ++i) {
count[i] = 0;
}

for (int i = 0; i < n; i++) {
count[a[i]]++;
}

for (int i = 1; i <= max; i++) count[i] += count[i - 1];

for (int i = n - 1; i >= 0; i--) {
output[count[a[i]] - 1] = a[i];
count[a[i]]--;
}

for (int i = 0; i < n; i++) {
a[i] = output[i];
}
}

/* Function to print the array elements */
void printArray(int a[], int n) {
int i;
for (i = 0; i < n; i++) System.out.print(a[i] + " ");
}

public static void main(String args[]) {
int a[] = {11, 30, 24, 7, 31, 16, 39, 41};
int n = a.length;
CountingSort c1 = new CountingSort();
System.out.println("\nBefore sorting array elements are - ");
c1.printArray(a, n);
c1.countSort(a, n);
System.out.println("\nAfter sorting array elements are - ");
c1.printArray(a, n);
System.out.println();
}
}