Skip to content

Instantly share code, notes, and snippets.

@codelance
Created December 2, 2012 00:57
Show Gist options
  • Save codelance/4186240 to your computer and use it in GitHub Desktop.
Save codelance/4186240 to your computer and use it in GitHub Desktop.
Java Selection Sort
public class SelectionSort {
/** The method for sorting the numbers */
/*
* Worst Case: O(n^2)
*/
public static void selectionSort(double[] list) {
for (int i = 0; i < list.length - 1; i++) {//Runs n times
// Find the minimum in the list[i..list.length-1]
//Get each element in the list for comparisons
//specifically get the smallest element in the list
double currentMin = list[i];
int currentMinIndex = i;
for (int j = i + 1; j < list.length; j++) { //Run n* (n-1) times
if (currentMin > list[j]) { //n * (n-2) times
currentMin = list[j];
currentMinIndex = j;
}
}
// Swap list[i] with list[currentMinIndex] if necessary;
if (currentMinIndex != i) { //Run n* (n-1) times
list[currentMinIndex] = list[i];
list[i] = currentMin;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment