Skip to content

Instantly share code, notes, and snippets.

@izeye
Created February 17, 2012 16:42
Show Gist options
  • Save izeye/1854292 to your computer and use it in GitHub Desktop.
Save izeye/1854292 to your computer and use it in GitHub Desktop.
Counting Sort (Java Version)
public class CountingSorter implements Sorter {
private final int maxValue;
public CountingSorter(int maxValue) {
this.maxValue = maxValue;
}
@Override
public int[] sort(int[] values) {
int[] counts = new int[maxValue + 1];
for (int i = 0; i < values.length; i++) {
counts[values[i]]++;
}
int total = 0;
for (int i = 0; i <= maxValue; i++) {
int count = counts[i];
counts[i] = total;
total += count;
}
int[] sortedValues = new int[values.length];
for (int i = 0; i < values.length; i++) {
sortedValues[counts[values[i]]] = values[i];
counts[values[i]]++;
}
return sortedValues;
}
}
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import org.junit.Test;
public class CountingSorterTest {
@Test
public void testSort() {
int maxScore = 100;
int[] expectedSortedScores = { 60, 80, 80, 100 };
int[] scores = { 80, 80, 60, 100 };
Sorter sorter = new CountingSorter(maxScore);
int[] sortedScores = sorter.sort(scores);
assertThat(sortedScores, is(expectedSortedScores));
}
}
public interface Sorter {
int[] sort(int[] values);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment