InsertionSort
Java
private static void insertionSort(int[] array) { for (int i = 1; i < array.length; ++i) { int index = i - 1, mark = array[i]; while (mark < array[index]) { array[index + 1] = array[index]; index--; if (index == -1) { break; } } array[index + 1] = mark; } }
private static void insertionSort(int[] array) { int index, mark; for (int i = 1; i < array.length; i++) { index = i - 1; mark = array[i]; while (index >= 0) { if (array[index] > mark) { array[index + 1] = array[index]; } else { // array[index + 1] = mark; // wrong, when mark is the minimum, array[index+1] = mark; is not executed break; } index--; } array[index + 1] = mark; } }
private static void insertionSort(int[] array) { int cursor, key; for (int i = 1; i < array.length; ++i) { key = array[i]; for (cursor = i - 1; cursor >= 0; --cursor) { if (array[cursor] <= key) { break; } array[cursor + 1] = array[cursor]; } array[cursor + 1] = key; } }