Created
December 2, 2012 00:57
-
-
Save codelance/4186240 to your computer and use it in GitHub Desktop.
Java Selection Sort
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 { | |
/** 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