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
keyvariable and loop indices, requiringO(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)
- Let the input array have
nelements at indices0ton - 1. Subarrayarr[0..0]is initially considered sorted. - Run an outer loop
ifrom1ton - 1. - Store the current element to be placed: set
key = arr[i]and initializej = i - 1. - While
j ≥ 0andarr[j] > key:- Shift element
arr[j]one slot to the right:arr[j + 1] = arr[j]. - Decrement
j = j - 1to check earlier elements in the sorted left prefix.
- Shift element
- Place
keyat its target slot:arr[j + 1] = key. - Repeat until
ireachesn - 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) → shift40right to index 1;jbecomes-1. - Insert
20atj + 1 = 0→[20, 40 | 30, 10].
- Compare
- Step 2 (
i = 2,key = 30):- Compare
40 > 30(j = 1) → shift40right to index 2;jbecomes0. - Compare
20 > 30? False (20 ≤ 30), so stop shifting. - Insert
30atj + 1 = 1→[20, 30, 40 | 10].
- Compare
- Step 3 (
i = 3,key = 10):40 > 10→ shift right;30 > 10→ shift right;20 > 10→ shift right;jbecomes-1.- Insert
10atj + 1 = 0→[10, 20, 30, 40](sorted).
Graphical Representation: Stepwise Passes of Insertion Sort on [40, 20, 30, 10]
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]