Insertion Sort Algorithm in DSA C# - Time & Space Complexity
We want to understand how the time taken by the Insertion Sort algorithm changes as the list size grows.
How does the number of steps increase when sorting bigger lists?
Analyze the time complexity of the following code snippet.
for (int i = 1; i < arr.Length; i++) {
int key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
This code sorts an array by inserting each element into its correct place among the already sorted elements on the left.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: The inner while loop that shifts elements to insert the key.
- How many times: The outer for loop runs once for each element (n-1 times), and the inner loop can run up to i times for each outer step.
As the list grows, the number of comparisons and shifts grows roughly with the square of the size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 45 comparisons and shifts |
| 100 | About 5,000 comparisons and shifts |
| 1000 | About 500,000 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 faster because the inner loop does fewer shifts.
Knowing how Insertion Sort behaves helps you understand sorting basics and compare with faster methods, which is a useful skill in interviews.
"What if we used a binary search to find the insertion point? How would the time complexity change?"
Practice
Insertion Sort algorithm?Solution
Step 1: Understand insertion sort process
Insertion sort takes one element at a time and inserts it into the correct position in the already sorted part of the array.Step 2: Compare with other sorting methods
Other options describe merge sort (B), bubble sort (C), and selection sort (D), which are different algorithms.Final Answer:
It builds the sorted array one element at a time by inserting elements in their correct position. -> Option AQuick Check:
Insertion sort = Insert elements step-by-step [OK]
- Confusing insertion sort with bubble sort
- Thinking insertion sort divides array recursively
- Mixing up selection sort with insertion sort
arr of length n?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 conditions
The loop runs whilei < nto cover all elements. for (int i = 1; i < n; i++) matches this.Final Answer:
for (int i = 1; i < n; i++) -> Option DQuick Check:
Start from 1 to n-1 for insertion sort loop [OK]
- Starting loop at 0 instead of 1
- Using <= n instead of < n causing out-of-bounds
- Counting backwards incorrectly
int[] arr = {4, 3, 2, 1}?Solution
Step 1: Trace insertion sort on given array
Start with 4 (sorted). Insert 3 before 4 -> [3,4,2,1]. Insert 2 before 3 -> [2,3,4,1]. Insert 1 before 2 -> [1,2,3,4].Step 2: Confirm final sorted array
The array is sorted in ascending order: [1, 2, 3, 4].Final Answer:
[1, 2, 3, 4] -> Option CQuick Check:
Insertion sort sorts ascending -> [1, 2, 3, 4] [OK]
- Assuming array stays unchanged
- Mixing up positions during insertion
- Stopping before fully sorting
for (int i = 1; i < arr.Length; i++) {
int key = arr[i];
int j = i + 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}Solution
Step 1: Check initialization of j
In insertion sort, j starts at the element before i, so it should bei - 1, noti + 1.Step 2: Verify while loop condition and shifting
The conditionj >= 0is correct to move backwards. The shifting logic is correct if j starts properly.Final Answer:
The variable j should start at i - 1 instead of i + 1. -> Option AQuick Check:
j starts at i-1 to compare previous elements [OK]
- Starting j at i+1 causing wrong comparisons
- Incorrect while loop boundary causing errors
- Misplacing key assignment inside loop
int[] arr = {1, 2, 4, 3, 5, 6}, how many element shifts will insertion sort perform to fully sort it?Solution
Step 1: Identify where shifts occur
Only the element 3 is out of order. It needs to be inserted before 4.Step 2: Count shifts to insert 3
To insert 3, j=2 (arr[2]=4 > 3), shift arr[3]=arr[2] (1 shift), j=1 (arr[1]=2 < 3), stop. Place arr[2]=3 (not a shift).Step 3: Check if other shifts occur
No other elements need shifting. Total shifts = 1.Final Answer:
1 -> Option BQuick Check:
One shift when inserting 3 [OK]
- Counting swaps instead of shifts
- Ignoring that placing key is not a shift
- Assuming all elements shift
Ready to prove it?
Pass the test and this pattern moves unknown
