NOIDATUT FREE E LEARNING PLATFORM • AKTU B.TECH

Insertion Sort in Data Structure

Insertion sort builds a sorted list one element at a time by taking each item from the unsorted part and shifting larger sorted elements right to insert it in place. It runs in O(n) best time, O(n²) average/worst time, and O(1) space.


Theory & Explanation

Insertion Sort: Definition, Stepwise Working, Complexity & Code

1. Definition & Key Characteristics

Insertion Sort is a simple comparison-based sorting algorithm that builds a sorted subarray one element at a time. It treats the first element (index 0) as already sorted and, in each step, picks the next element (key) from the unsorted portion, shifts all larger elements in the sorted left portion one position to the right, and inserts key into its proper sorted position—much like sorting playing cards in your hand.

  • In-Place Algorithm: Sorts the array directly using only a key variable and loop indices, requiring O(1) auxiliary space.
  • Stable Sorting Algorithm: Preserves the relative order of equal keys because shifting stops as soon as arr[j] ≤ key.
  • Adaptive & Online: Runs in O(n) time on already or nearly sorted data, and can sort elements as they arrive (streaming/online input).

2. How Insertion Sort Works (Step-by-Step Algorithm)

  1. Let the input array have n elements at indices 0 to n - 1. Subarray arr[0..0] is initially considered sorted.
  2. Run an outer loop i from 1 to n - 1.
  3. Store the current element to be placed: set key = arr[i] and initialize j = i - 1.
  4. While j ≥ 0 and arr[j] > key:
    • Shift element arr[j] one slot to the right: arr[j + 1] = arr[j].
    • Decrement j = j - 1 to check earlier elements in the sorted left prefix.
  5. Place key at its target slot: arr[j + 1] = key.
  6. Repeat until i reaches n - 1; the entire array is then sorted.

3. Step-by-Step Example & Graphical Representation

Sort arr = [40, 20, 30, 10] (n = 4) in ascending order:

  • Initial (i = 0): [40 | 20, 30, 10] → [40] is the initial sorted prefix.
  • Step 1 (i = 1, key = 20):
    • Compare 40 > 20 (j = 0) → shift 40 right to index 1; j becomes -1.
    • Insert 20 at j + 1 = 0 → [20, 40 | 30, 10].
  • Step 2 (i = 2, key = 30):
    • Compare 40 > 30 (j = 1) → shift 40 right to index 2; j becomes 0.
    • Compare 20 > 30? False (20 ≤ 30), so stop shifting.
    • Insert 30 at j + 1 = 1 → [20, 30, 40 | 10].
  • Step 3 (i = 3, key = 10):
    • 40 > 10 → shift right; 30 > 10 → shift right; 20 > 10 → shift right; j becomes -1.
    • Insert 10 at j + 1 = 0 → [10, 20, 30, 40] (sorted).

Graphical Representation: Stepwise Passes of Insertion Sort on [40, 20, 30, 10]

Insertion Sort Step-by-Step Trace (Ascending): [40, 20, 30, 10] → [10, 20, 30, 40] Initial: 40 20 30 10 40 is initial sorted prefix; rest unsorted Step 1: 20 40 30 10 key=20: shifted 40 right, inserted at idx 0 Step 2: 20 30 40 10 key=30: shifted 40 right, inserted at idx 1 Step 3: 10 20 30 40 key=10: shifted 20..40 right, inserted at idx 0 Green = sorted left subarray | Amber = remaining unsorted elements to be inserted

4. Time & Space Complexity Analysis

Case Condition Comparisons Shifts Time Complexity
Best Case Array is already sorted n - 1 0 O(n)
Average Case Randomly ordered elements ~n2/4 ~n2/4 O(n2)
Worst Case Array is sorted in reverse order n(n - 1)/2 n(n - 1)/2 O(n2)

Auxiliary Space Complexity: O(1) (in-place sorting).

5. C Program: Insertion Sort

#include <stdio.h>

void insertionSort(int arr[], int n) {
    for (int i = 1; i < n; i++) {
        int key = arr[i];
        int j = i - 1;

        // Shift elements of arr[0..i-1] that are greater than key
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j--;
        }
        arr[j + 1] = key;
    }
}

void printArray(int arr[], int n) {
    for (int i = 0; i < n; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {40, 20, 30, 10};
    int n = sizeof(arr) / sizeof(arr[0]);

    printf("Original array: ");
    printArray(arr, n);

    insertionSort(arr, n);

    printf("Sorted array (Ascending): ");
    printArray(arr, n);

    return 0;
}

Expected Output (C):

Original array: 40 20 30 10 
Sorted array (Ascending): 10 20 30 40 

6. Python Program: Insertion Sort

def insertion_sort(arr):
    for i in range(1, len(arr)):
        key = arr[i]
        j = i - 1

        while j >= 0 and arr[j] > key:
            arr[j + 1] = arr[j]
            j -= 1

        arr[j + 1] = key
    return arr


if __name__ == "__main__":
    data = [40, 20, 30, 10]
    print("Original array:", data)
    sorted_data = insertion_sort(data[:])
    print("Sorted array (Ascending):", sorted_data)

Expected Output (Python):

Original array: [40, 20, 30, 10]
Sorted array (Ascending): [10, 20, 30, 40]
Advertisement
Advertisement