Created
May 22, 2010 11:30
-
-
Save Tetha/410009 to your computer and use it in GitHub Desktop.
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 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