Skip to content

Instantly share code, notes, and snippets.

@Tetha
Created May 22, 2010 11:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tetha/410009 to your computer and use it in GitHub Desktop.
Save Tetha/410009 to your computer and use it in GitHub Desktop.
public class SelectionSort {
private static int[] selectionSort(int[] values) {
for(int firstUnsortedIndex = 0;
firstUnsortedIndex < values.length;
firstUnsortedIndex++) {
swapValuesAt(values,
firstUnsortedIndex,
findIndexOfSmallestValueAfter(values, firstUnsortedIndex));
}
return values;
}
private static int findIndexOfSmallestValueAfter(int[] values, int startIndex) {
int smallestValueSoFar = -1;
int smallestValueIndex = -1;
for (int candidateIndex = startIndex;
candidateIndex < values.length;
candidateIndex++) {
int candidateValue = values[candidateIndex];
if (isFirstValue(candidateIndex)
|| candidateValue < smallestValueSoFar) {
smallestValueSoFar = candidateValue;
smallestValueIndex = candidateIndex;
}
}
return smallestValueIndex;
}
private static boolean isFirstValue(int candidateIndex) {
return candidateIndex == 0;
}
private static void swapValuesAt(int[] values,
int firstIndex,
int secondIndex) {
int firstValue = values[firstIndex];
int secondValue = values[secondIndex];
values[firstIndex] = secondValue;
values[secondIndex] = firstValue;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment