0
0
DSA Javascriptprogramming

Insertion Sort Algorithm in DSA Javascript

Choose your learning style9 modes available
Mental Model
Insertion sort builds a sorted list one item at a time by placing each new item into its correct position.
Analogy: Imagine sorting playing cards in your hand by picking one card at a time and inserting it into the right spot among the cards you already sorted.
Unsorted array:
[5, 3, 8, 4, 2]

Sorted portion ↑
[5, 3, 8, 4, 2]
 ↑
Dry Run Walkthrough
Input: array: [5, 3, 8, 4, 2]
Goal: Sort the array in ascending order using insertion sort
Step 1: Take element 3 and compare with 5, shift 5 right
[5, 5, 8, 4, 2] ↑ (insertion point found)
Why: We move 5 to the right to make space for 3 in the sorted part
Step 2: Insert 3 at position 0
[3, 5, 8, 4, 2] ↑
Why: 3 is smaller than 5, so it goes before 5
Step 3: Take element 8, no shift needed as 8 > 5
[3, 5, 8, 4, 2] ↑
Why: 8 is already in correct position
Step 4: Take element 4, shift 8 and 5 right to insert 4
[3, 5, 8, 8, 2] ↑
Why: We move 8 right to make space for 4
Step 5: Shift 5 right to continue making space for 4
[3, 5, 5, 8, 2] ↑
Why: 5 is greater than 4, so it moves right
Step 6: Insert 4 at position 1
[3, 4, 5, 8, 2] ↑
Why: 4 fits between 3 and 5
Step 7: Take element 2, shift 8, 5, 4, 3 right to insert 2
[3, 4, 5, 8, 8] ↑
Why: Shift 8 right to make space for 2
Step 8: Shift 5 right
[3, 4, 5, 5, 8] ↑
Why: Shift 5 right to continue making space
Step 9: Shift 4 right
[3, 4, 4, 5, 8] ↑
Why: Shift 4 right to continue making space
Step 10: Shift 3 right
[3, 3, 4, 5, 8] ↑
Why: Shift 3 right to continue making space
Step 11: Insert 2 at position 0
[2, 3, 4, 5, 8] ↑
Why: 2 is smallest, goes at start
Result:
[2, 3, 4, 5, 8]
Annotated Code
DSA Javascript
class InsertionSort {
  static sort(arr) {
    for (let i = 1; i < arr.length; i++) {
      let key = arr[i];
      let j = i - 1;
      // Move elements greater than key one position ahead
      while (j >= 0 && arr[j] > key) {
        arr[j + 1] = arr[j];
        j--;
      }
      arr[j + 1] = key;
    }
    return arr;
  }
}

// Driver code
const array = [5, 3, 8, 4, 2];
const sortedArray = InsertionSort.sort(array);
console.log(sortedArray.join(", ") + "\n");
for (let i = 1; i < arr.length; i++) {
iterate over each element starting from second to insert it correctly
let key = arr[i];
store current element to insert
while (j >= 0 && arr[j] > key) {
shift elements greater than key to the right
arr[j + 1] = arr[j];
move element one position right to make space
j--;
move left to compare next element
arr[j + 1] = key;
insert key at correct sorted position
OutputSuccess
2, 3, 4, 5, 8
Complexity Analysis
Time: O(n^2) because in worst case each element is compared and shifted with all previous elements
Space: O(1) because sorting is done in place without extra storage
vs Alternative: Compared to bubble sort, insertion sort is often faster on nearly sorted data because it stops shifting early
Edge Cases
empty array
returns empty array immediately without errors
DSA Javascript
for (let i = 1; i < arr.length; i++) {
array with one element
returns the same single-element array as sorted
DSA Javascript
for (let i = 1; i < arr.length; i++) {
array with all elements equal
no shifts occur, returns the same array
DSA Javascript
while (j >= 0 && arr[j] > key) {
When to Use This Pattern
When you need to sort a small or nearly sorted list by inserting elements one by one, reach for insertion sort because it builds the sorted list gradually and efficiently.
Common Mistakes
Mistake: Not shifting elements to the right before inserting the key, causing overwriting values
Fix: Use a while loop to shift all elements greater than key one position right before inserting key
Mistake: Starting the outer loop from index 0 instead of 1
Fix: Start from index 1 because the first element is trivially sorted
Summary
Insertion sort builds a sorted array by inserting each element into its correct position.
Use it for small or nearly sorted arrays where simple insertion is efficient.
The key insight is shifting larger elements right to make space for the current element.