Below is an example of the Insertion Sort algorithm in Java. See the Insertion Sort page for more information and implementations.
public static void main(String[] args) { int[] array = {12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8}; insertionSort(array); System.out.println(java.util.Arrays.toString(array)); } static void insertionSort(int[] array) { // start at the first index and iterate through to the end for (int i = 1; i < array.length; i++) { int currentIndex = i; /* * Check: * 1. that currentIndex is at least 1 * 2. that the item directly before the currentIndex is greater than the item at currentIndex * * If both conditions are met, swap the indexes */ while (currentIndex > 0 && array[currentIndex - 1] > array[currentIndex]) { int temp = array[currentIndex]; array[currentIndex] = array[currentIndex - 1]; array[currentIndex - 1] = temp; currentIndex--; } } }