allizwell.jobsdoor360.in

Insertion Sort

Data Structures and Algorithms / Searching and Sorting / Insertion Sort

Insertion Sort in C++

Insertion Sort is a simple comparison-based sorting algorithm that builds a sorted array one element at a time. It takes each element from the unsorted portion and inserts it into its correct position in the sorted portion. It is especially useful for small datasets and arrays that are already nearly sorted.

1. What Is Insertion Sort?

Insertion Sort works similarly to arranging playing cards in your hand. You pick one card at a time and insert it into the correct position among the cards that are already arranged.

In an array, the algorithm considers the first element as a sorted portion. It then takes the next element, compares it with the elements before it, shifts larger elements one position to the right, and inserts the selected element at its correct position.

Example

Consider this unsorted array:

arr = {5, 3, 4, 1, 2}

After applying Insertion Sort:

arr = {1, 2, 3, 4, 5}

2. How Does Insertion Sort Work?

Insertion Sort divides the array into two logical portions:

  • Sorted portion: Elements that have already been arranged in sorted order.
  • Unsorted portion: Elements that still need to be inserted into their correct positions.

The algorithm follows these steps:

  1. Assume the first element is already sorted.
  2. Select the next element. This element is called the key.
  3. Compare the key with the elements in the sorted portion.
  4. Shift every element greater than the key one position to the right.
  5. Insert the key into the empty position created by shifting.
  6. Repeat until all elements are processed.
Important: In ascending Insertion Sort, elements greater than the key are shifted to the right, making space for the key at its correct position.

3. Understanding Insertion Sort Step by Step

Consider the following array:

arr = {5, 3, 4, 1, 2}

Initial State

The first element, 5, is considered sorted.

{5 | 3, 4, 1, 2}

Pass 1: Insert 3

The key is 3. Compare it with 5. Since 5 is greater than 3, shift 5 to the right and insert 3.

{3, 5 | 4, 1, 2}

Pass 2: Insert 4

The key is 4. Compare it with 5. Since 5 is greater than 4, shift 5 to the right. Insert 4 after 3.

{3, 4, 5 | 1, 2}

Pass 3: Insert 1

The key is 1. It is smaller than 5, 4, and 3. Shift these elements to the right and insert 1 at the beginning.

{1, 3, 4, 5 | 2}

Pass 4: Insert 2

The key is 2. Shift 5, 4, and 3 to the right. Insert 2 immediately after 1.

{1, 2, 3, 4, 5}

Final Sorted Array: 1 2 3 4 5

4. Insertion Sort Algorithm

The algorithm uses a loop to select each element and another loop to shift larger elements toward the right.

Pseudocode

InsertionSort(arr, n):

    for i = 1 to n - 1:

        key = arr[i]

        j = i - 1

        while j >= 0 AND arr[j] > key:

            arr[j + 1] = arr[j]

            j = j - 1

        arr[j + 1] = key

5. C++ Code: Insertion Sort

The following program implements Insertion Sort in ascending order.

#include <iostream>
#include <vector>
using namespace std;

void insertionSort(vector<int>& arr) {

    int n = arr.size();

    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;
    }
}

int main() {

    vector<int> arr = {5, 3, 4, 1, 2};

    insertionSort(arr);

    cout << "Sorted Array: ";

    for (int x : arr) {
        cout << x << " ";
    }

    return 0;
}

Output

Sorted Array: 1 2 3 4 5

6. Understanding the Code

Outer Loop

for (int i = 1; i < n; i++)

The outer loop starts from index 1 because the first element is already considered sorted.

Key Element

int key = arr[i];

The key stores the element that must be inserted into the correct position in the sorted portion.

Previous Index

int j = i - 1;

The variable j points to the element immediately before the key. It moves toward the beginning of the array while larger elements are found.

Shifting Elements

while (j >= 0 && arr[j] > key) {
    arr[j + 1] = arr[j];
    j--;
}

This loop shifts every element greater than the key one position to the right.

Inserting the Key

arr[j + 1] = key;

When the shifting loop stops, j + 1 represents the correct position for the key.

Remember: The key must be stored in a separate variable before shifting. Otherwise, its original value could be overwritten.

7. Dry Run of Insertion Sort

Consider the array:

arr = {8, 4, 6, 2, 5}
Pass Key Elements Shifted Array After Insertion
Initial - - 8, 4, 6, 2, 5
1 4 8 4, 8, 6, 2, 5
2 6 8 4, 6, 8, 2, 5
3 2 8, 6, 4 2, 4, 6, 8, 5
4 5 8, 6 2, 4, 5, 6, 8

Final Sorted Array: 2 4 5 6 8

8. Insertion Sort in Descending Order

To arrange elements in descending order, we need to shift elements smaller than the key toward the right.

For ascending order:

while (j >= 0 && arr[j] > key)

For descending order:

while (j >= 0 && arr[j] < key)

C++ Code: Descending Insertion Sort

#include <iostream>
#include <vector>
using namespace std;

void insertionSortDescending(vector<int>& arr) {

    int n = arr.size();

    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;
    }
}

int main() {

    vector<int> arr = {5, 3, 8, 4, 2};

    insertionSortDescending(arr);

    cout << "Descending Array: ";

    for (int x : arr) {
        cout << x << " ";
    }

    return 0;
}

Output

Descending Array: 8 5 4 3 2

9. Optimized Insertion Sort

The standard Insertion Sort implementation is already adaptive. It performs fewer operations when the array is nearly sorted.

We can also avoid unnecessary assignments by checking whether the key is already greater than or equal to the last element of the sorted portion.

C++ Code: Insertion Sort with an Early Check

#include <iostream>
#include <vector>
using namespace std;

void insertionSort(vector<int>& arr) {

    int n = arr.size();

    for (int i = 1; i < n; i++) {

        int key = arr[i];

        // Already in correct position
        if (arr[i - 1] <= key) {
            continue;
        }

        int j = i - 1;

        while (j >= 0 && arr[j] > key) {

            arr[j + 1] = arr[j];

            j--;
        }

        arr[j + 1] = key;
    }
}

int main() {

    vector<int> arr = {1, 2, 3, 4, 5};

    insertionSort(arr);

    cout << "Sorted Array: ";

    for (int x : arr) {
        cout << x << " ";
    }

    return 0;
}

Output

Sorted Array: 1 2 3 4 5

Important: This early check avoids unnecessary key insertion work when the key is already in the correct position. It does not change the asymptotic time complexity.

10. Time Complexity of Insertion Sort

Best Case

The best case occurs when the array is already sorted. Each key is compared with the previous element once, and no shifting is required.

Best Case: O(n)

Average Case

In the average case, elements are in random order. The algorithm performs multiple comparisons and shifts.

Average Case: O(n²)

Worst Case

The worst case occurs when the array is sorted in reverse order for ascending sorting.

Every new key must be shifted past all previously processed elements.

Worst Case: O(n²)

11. Number of Comparisons and Shifts

In the worst case, the first key may require one comparison, the second key may require two, and so on.

Comparisons = 1 + 2 + 3 + ... + (n - 1)

Using the arithmetic series formula:

Worst-case comparisons = n * (n - 1) / 2

The number of shifts can also reach:

Worst-case shifts = n * (n - 1) / 2

Example

For an array containing 5 elements in reverse order:

arr = {5, 4, 3, 2, 1}

Maximum shifts = 5 * 4 / 2
               = 10

12. Space Complexity of Insertion Sort

Insertion Sort rearranges the elements inside the original array. It uses only a few additional variables such as key, i, and j.

Auxiliary Space Complexity: O(1)

Therefore, Insertion Sort is an in-place sorting algorithm.

13. Complexity Summary

Case or Property Complexity
Best Case Time O(n)
Average Case Time O(n²)
Worst Case Time O(n²)
Auxiliary Space O(1)
Worst-case Comparisons O(n²)
Worst-case Shifts O(n²)

14. Properties of Insertion Sort

Property Description
Algorithm Type Comparison-based sorting
Sorting Method Inserting each key into its correct position
In-place Yes
Stable Yes, with the strict greater-than comparison
Adaptive Yes
Best Case O(n)
Worst Case O(n²)
Auxiliary Space O(1)

Is Insertion Sort Stable?

Yes. Insertion Sort is stable when it shifts elements only when they are strictly greater than the key.

Equal elements are not moved past one another, so their original relative order is preserved.

Is Insertion Sort In-place?

Yes. It sorts the array using the original storage and requires only a constant amount of additional memory.

Is Insertion Sort Adaptive?

Yes. Its running time depends on how close the input is to being sorted. Nearly sorted arrays require fewer shifts and comparisons.

15. Insertion Sort vs Bubble Sort vs Selection Sort

Feature Bubble Sort Selection Sort Insertion Sort
Basic Idea Adjacent swapping Select minimum element Insert key in correct position
Best Case O(n), optimized O(n²) O(n)
Average Case O(n²) O(n²) O(n²)
Worst Case O(n²) O(n²) O(n²)
Auxiliary Space O(1) O(1) O(1)
Stable Yes No, standard version Yes
Adaptive Yes, optimized No Yes

16. Advantages of Insertion Sort

  • Simple to understand and implement.
  • Works efficiently for small datasets.
  • Performs well on nearly sorted arrays.
  • Requires only O(1) auxiliary space.
  • It is stable when implemented with the strict greater-than condition.
  • Can sort elements as they arrive one by one.

17. Disadvantages of Insertion Sort

  • Average and worst-case time complexity is O(n²).
  • It performs many shifts when elements are far from their correct positions.
  • It is inefficient for large, randomly ordered datasets.
  • Its performance can be much slower than Merge Sort and other efficient algorithms on large inputs.

18. Applications of Insertion Sort

  • Sorting small datasets.
  • Sorting arrays that are already nearly sorted.
  • Maintaining a sorted list while new elements are inserted.
  • Online sorting, where elements arrive one at a time.
  • As a small-array sorting technique inside some hybrid sorting algorithms.

19. Common Mistakes

  • Starting the outer loop at index 0: Start at index 1 because the first element is already considered sorted.
  • Not storing the key: Save arr[i] in a separate variable before shifting elements.
  • Incorrect while condition: Check j >= 0 before accessing arr[j].
  • Using the wrong comparison: Use arr[j] > key for ascending order.
  • Incorrect insertion index: Insert the key at arr[j + 1], not arr[j].
  • Swapping instead of shifting: Standard Insertion Sort shifts larger elements to the right rather than repeatedly swapping adjacent elements.
  • Confusing average and best cases: The best case is O(n), but the average and worst cases are O(n²).

20. Interview Questions

  1. What is Insertion Sort?
  2. How does Insertion Sort work?
  3. What is the key element in Insertion Sort?
  4. Why does the outer loop start from index 1?
  5. What is the time complexity of Insertion Sort?
  6. Why is its best-case time complexity O(n)?
  7. What is its worst-case time complexity?
  8. Is Insertion Sort stable? Why?
  9. Is Insertion Sort an in-place algorithm?
  10. What makes Insertion Sort adaptive?
  11. Why are elements shifted instead of repeatedly swapped?
  12. When should Insertion Sort be preferred?
  13. How can Insertion Sort arrange elements in descending order?
  14. What is the difference between Insertion Sort and Selection Sort?

21. Practice Problems

Problem 1: Sort an Array Using Insertion Sort

Given an array of integers, sort it in ascending order using Insertion Sort.

Input:
{5, 3, 4, 1, 2}

Output:
{1, 2, 3, 4, 5}

Problem 2: Sort an Array in Descending Order

Modify Insertion Sort to arrange the elements from largest to smallest.

Input:
{5, 3, 8, 4, 2}

Output:
{8, 5, 4, 3, 2}

Problem 3: Count Shifts in Insertion Sort

Modify the algorithm to count how many shifts are performed while sorting the array.

Input:
{4, 3, 2, 1}

Output:
6

Problem 4: Sort a Nearly Sorted Array

Use Insertion Sort to arrange an array in which most elements are already close to their correct positions.

Input:
{1, 3, 2, 4, 5}

Output:
{1, 2, 3, 4, 5}

Problem 5: Sort an Array with Duplicate Elements

Implement Insertion Sort for an array containing duplicate values and preserve the relative order of equal elements.

Input:
{4, 2, 4, 1, 2}

Output:
{1, 2, 2, 4, 4}

22. Summary

  • Insertion Sort builds a sorted portion one element at a time.
  • It selects a key from the unsorted portion.
  • Elements greater than the key are shifted to the right.
  • The key is inserted into its correct position.
  • Its best-case time complexity is O(n).
  • Its average and worst-case time complexity is O(n²).
  • Its auxiliary space complexity is O(1).
  • It is stable, in-place, and adaptive.
  • It works particularly well for small and nearly sorted datasets.
Key Takeaway: Insertion Sort repeatedly takes an element and inserts it into its correct position in the sorted portion of an array. It is simple, stable, in-place, and efficient for small or nearly sorted datasets. Its best-case time complexity is O(n), while its average and worst-case time complexity is O(n²).
Scroll to Top