0
0
DSA C++programming~5 mins

Insertion Sort Algorithm in DSA C++ - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Insertion Sort Algorithm
O(n²)
Understanding Time 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?

Scenario Under Consideration

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 Repeating Operations

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.
How Execution Grows With Input

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
10About 45 comparisons and shifts
100About 4,950 comparisons and shifts
1000About 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.

Final Time Complexity

Time Complexity: O(n²)

This means the time taken grows roughly with the square of the number of items to sort.

Common Mistake

[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.

Interview Connect

Understanding Insertion Sort's time complexity helps you explain sorting basics clearly and compare simple algorithms to more advanced ones.

Self-Check

"What if we changed the array to be nearly sorted? How would the time complexity change?"