Created
December 2, 2012 00:56
-
-
Save codelance/4186234 to your computer and use it in GitHub Desktop.
Java Insert 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 InsertionSort { | |
/** The method for sorting the numbers */ | |
/* | |
* Worst Case: O(n^2) | |
*/ | |
public static void insertionSort(double[] list) { | |
for (int i = 1; i < list.length; i++) { ///Runs n times | |
/** insert list[i] into a sorted sublist list[0..i-1] so that | |
list[0..i] is sorted. */ | |
//traverse the list linearly and get each element for comparison. | |
double currentElement = list[i]; //Runs n - 1 times | |
int k; | |
//Loop gets the element preceeding above and places each element | |
// in the current index the for loop as long as the element obtained | |
//greater then the current index being processed. | |
for (k = i - 1; k >= 0 && list[k] > currentElement; k--) { //Runs n * (n - 2) times | |
list[k + 1] = list[k]; //Runs n - 1 times | |
} | |
// Insert the current element into list[k+1] | |
//Put the element back in the list once all elements bigger | |
//than it have been placed before it. | |
list[k + 1] = currentElement; // Will run n - 1 | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment