Insertion Sort is a way to sort a list by gradually building up a sorted part. It is like sorting playing cards in your hands. You split the cards into two groups: the sorted cards and the unsorted cards. Then, pick a card from the unsorted group and put it in the right place in the sorted group.
Here is actually how the Insertion Sort works:
Insertion sort animation
Illustration of Insertion Sort
const insertionSort = (arr) => { let sortedArr = [...arr]; // A copy of the array for(let i = 1; i < sortedArr.length; i++) { let key = arr[i]; let j = i - 1; /* Move elements of arr[0..i-1], that are greater than key, to one position ahead of their current position */ while (j >= 0 && sortedArr[j] > key) { sortedArr[j + 1] = sortedArr[j]; j -= 1; } sortedArr[j + 1] = key; } return sortedArr; }; const arr = [23, 1, 10, 5, 2]; document.getElementById('originalArray').textContent = "Original Array: " + arr; const sortedArr = insertionSort(arr); document.getElementById('sortedArray').textContent = "Sorted Array: " + sortedArr;
The initial array: [23, 1, 10, 5, 2].
The first element (23) is considered sorted by itself. 23 > 1? → [1, 23, 10, 5, 2] 23 > 10? → [1, 10, 23, 5, 2] 23 > 5? → [1, 10, 5, 23, 2], 10 > 5? → [1, 5, 10, 23, 2], 5 > 1? → [1, 5, 10, 23, 2] 23 > 2? → [1, 5, 10, 2, 23], 10 > 2? → [1, 5, 2, 10, 23], 5 > 2? → [1, 2, 5, 10, 23], 2 > 1? → [1, 2, 5, 10, 23]
Simplicity: Easy to implement & understand.
Efficiency on Small Data: Stable and works quickly on small or nearly sorted arrays, though its worst-case time complexity is O(n2).
Practically: Often used in hubrid sorts for its simplicity and low space complexity (O(1) extra space).
Insertion sort & Bubble sort: Insertion sort inserts each element into its correct position with fewer moves, while Bubble sort repeatedly swaps adjacent elements, making insertion sort typically more efficient on small or nearly sorted data.