Lesson 3 of 20
Insertion Sort
Insertion Sort
Insertion Sort builds the sorted array one element at a time. Think of sorting a hand of playing cards: you pick up each card and insert it into the correct position among the cards you already hold.
How It Works
- Start with the second element (index 1). The first element is trivially sorted.
- Store the current element as
key. - Shift all sorted elements that are greater than
keyone position to the right. - Insert
keyinto the gap. - Move to the next element and repeat.
function insertionSort(arr) {
const a = [...arr];
for (let i = 1; i < a.length; i++) {
const key = a[i];
let j = i - 1;
while (j >= 0 && a[j] > key) {
a[j + 1] = a[j];
j--;
}
a[j + 1] = key;
}
return a;
}
Complexity
| Case | Time | Space |
|---|---|---|
| Best (sorted) | O(n) | O(1) |
| Average | O(n²) | O(1) |
| Worst (reversed) | O(n²) | O(1) |
Insertion sort is excellent for nearly sorted arrays and small datasets. Many production sort implementations (like Timsort) use insertion sort for small subarrays.
Your Task
Implement insertionSort(arr) that returns a new array sorted in ascending order.
JavaScript loading...
Loading...
Click "Run" to execute your code.