Insertion sort
Easy TimeO(n²) SpaceO(1)
Given an array arr of numbers, sort it into ascending order in place by taking each value in turn and putting it where it belongs among the values already sorted to its left. After every step that left-hand part is sorted and one longer, and a value already in the right place does not move at all.
Examples
Example 1
- Input
- arr = [5, 2, 8, 1, 4]
- Output
- The same five values, ascending.
[1,2,4,5,8]
Example 2
- Input
- arr = [1, 2, 3, 0]
- Output
- The
[0,1,2,3]0belongs at the front, and the three values above it each shift one place right.
The Code
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
const key = arr[i];
let j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
return arr;
}
insertionSort([5, 2, 8, 1, 4]);Done
More like this
All sorting examples (8) →- Merge sort Divide and conquer — split in half, sort, then merge.
- Quick sort Pick a pivot, partition around it, recurse on each side.
- Bubble sort Repeatedly swap adjacent out-of-order pairs until sorted.
- Selection sort Find the smallest remaining element and swap it into place.
- Counting sort No comparisons — tally each value, then read the tallies back out.
- Heap sort Build a max-heap, then repeatedly move the root to the back.