Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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