Loading…
Loading…
Builds the sorted array one item at a time by inserting each new element into its correct place among the already-sorted prefix.
First element is trivially sorted.
1void insertionSort(int[] a) {2 for (int i = 1; i < a.length; i++) {3 int key = a[i];4 int j = i - 1;5 while (j >= 0 && a[j] > key) {6 a[j + 1] = a[j];7 j--;8 }9 a[j + 1] = key;10 }11}