Insertion Sort Algorithm in DSA Javascript - Time & Space Complexity
We want to understand how the time taken by the Insertion Sort algorithm changes as the list size grows.
Specifically, how many steps does it take to sort more numbers?
Analyze the time complexity of the following code snippet.
function insertionSort(arr) {
for (let i = 1; i < arr.length; i++) {
let 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;
}
This code sorts an array by inserting each element into its correct place among the already sorted elements to its left.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner while loop that shifts elements to insert the key in the right place.
- How many times: The outer for loop runs once for each element (n-1 times), and the inner while loop can run up to i times for each outer loop step.
As the list grows, the number of comparisons and shifts grows roughly with the square of the list size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 45 comparisons and shifts |
| 100 | About 4,950 comparisons and shifts |
| 1000 | About 499,500 comparisons and shifts |
Pattern observation: When input size doubles, operations roughly quadruple, showing a squared growth.
Time Complexity: O(n²)
This means the time taken grows roughly with the square of the number of items to sort.
[X] Wrong: "Insertion Sort always takes the same time no matter the input order."
[OK] Correct: If the list is already mostly sorted, Insertion Sort runs much faster, closer to linear time, because fewer shifts are needed.
Knowing how Insertion Sort behaves helps you understand sorting basics and compare it with faster methods, which is a useful skill in interviews and real coding.
"What if we changed the array to be already sorted? How would the time complexity change?"
Practice
Insertion Sort algorithm?Solution
Step 1: Understand insertion sort process
Insertion sort builds the sorted list by taking one element at a time and placing it in the correct position among the already sorted elements.Step 2: Compare with other sorting methods
Other options describe different algorithms: dividing (merge sort), swapping adjacent (bubble sort), selecting smallest (selection sort).Final Answer:
Build the sorted array one element at a time by inserting elements in the correct position -> Option AQuick Check:
Insertion sort = Insert elements step-by-step [OK]
- Confusing insertion sort with bubble sort
- Thinking it divides the array like merge sort
- Mixing it up with selection sort
arr?Solution
Step 1: Identify starting index for insertion sort
Insertion sort starts from the second element (index 1) because the first element is considered sorted.Step 2: Check loop condition correctness
The loop runs whilei < arr.lengthto cover all elements. Starting at 0 or going beyond length is incorrect.Final Answer:
for(let i = 1; i < arr.length; i++) -> Option BQuick Check:
Start loop at 1 for insertion sort [OK]
- Starting loop at 0 instead of 1
- Using <= instead of < in loop condition
- Looping backwards incorrectly
function insertionSort(arr) {
for(let i = 1; i < arr.length; i++) {
let 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;
}
console.log(insertionSort([4, 2, 7, 1]));Solution
Step 1: Trace first iteration (i=1)
key=2, compare with 4, shift 4 right, insert 2 at index 0 -> [2,4,7,1]Step 2: Trace remaining iterations
i=2: key=7, no shift -> [2,4,7,1]; i=3: key=1, shift 7,4,2 right, insert 1 at index 0 -> [1,2,4,7]Final Answer:
[1, 2, 4, 7] -> Option DQuick Check:
Sorted array = [1, 2, 4, 7] [OK]
- Not shifting elements correctly
- Returning original array without sorting
- Confusing key placement index
function insertionSort(arr) {
for(let i = 1; i <= arr.length; i++) {
let 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;
}Solution
Step 1: Check outer loop boundary
The loop runs from 1 to arr.length inclusive, but array indices go from 0 to arr.length - 1, soi < arr.lengthis correct.Step 2: Verify other parts
Inner loop condition and key assignment are correct;jstarts ati - 1to compare with previous elements.Final Answer:
The outer loop condition should bei < arr.lengthinstead of <=. -> Option AQuick Check:
Loop must not exceed array length [OK]
i < arr.length to avoid out-of-bounds [OK]- Using <= causes index out of range error
- Changing inner loop condition incorrectly
- Misplacing key assignment
[3, 0, -2, 5, 1], after the second iteration (i=2) of insertion sort, what will the array look like?Solution
Step 1: Trace first iteration (i=1)
key=0, compare with 3, shift 3 right, insert 0 at index 0 -> [0,3,-2,5,1]Step 2: Trace second iteration (i=2)
key=-2, compare with 3 and 0, shift both right, insert -2 at index 0 -> [-2,0,3,5,1]Final Answer:
[-2, 0, 3, 5, 1] -> Option CQuick Check:
After 2 iterations, array is partially sorted [OK]
- Not shifting all larger elements
- Inserting key at wrong position
- Confusing iteration count with index
Ready to prove it?
Pass the test and this pattern moves unknown
