Insertion Sort
Last updated
Last updated
// Note: In some cases the list may be sorted in reverse order.
public class InsertionSort extends ConsoleProgram
{
public void run()
{
// Create our array of integers to sort
int[] intsToSort = {1, 5, 6, 3};
// We start at `1` instead of `0`
// because first value is already sorted
for(int i = 1; i < intsToSort.length; i++)
{
int currNum = intsToSort[i];
// Shift element into designated position
int currIndex = i-1;
while(currIndex > -1 && intsToSort[currIndex] > currNum)
{
intsToSort[currIndex+1] = intsToSort[currIndex];
currIndex--;
}
intsToSort[currIndex+1] = currNum;
}
}
}