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[] arr) {2 for (int i = 1; i < arr.length; i++) { // grow sorted prefix3 int key = arr[i]; // element to insert4 int j = i - 1;5 while (j >= 0 && arr[j] > key) { // shift bigger ones right6 arr[j + 1] = arr[j];7 j--;8 }9 arr[j + 1] = key; // drop key into the gap10 }11}