Created
February 17, 2012 16:42
-
-
Save izeye/1854292 to your computer and use it in GitHub Desktop.
Counting Sort (Java Version)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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