Insertion Sort Algorithm in DSA C++ - Time & Space Complexity
We want to understand how the time taken by Insertion Sort changes as the list size grows.
How does the number of steps increase when sorting more items?
Analyze the time complexity of the following code snippet.
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; 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 position among the previously sorted elements.
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 n-1 times, and the inner while loop can run up to i times for each i from 1 to n-1.
As the list size grows, the number of comparisons and shifts increases roughly with the square of the size in the worst case.
| 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: The operations grow roughly by the square of the input size, so doubling the input makes the work about four times bigger.
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.
Understanding Insertion Sort's time complexity helps you explain sorting basics clearly and compare simple algorithms to more advanced ones.
"What if we changed the array to be nearly sorted? How would the time complexity change?"