Insertion Sort is a straightforward, intuitive comparison-based sorting algorithm. It works similarly to how you might sort a hand of playing cards: pick one card at a time and insert it into its correct position among the already sorted cards.
Insertion Sort is particularly efficient for small datasets and nearly sorted arrays, and it is known for being simple, stable, and easy to implement.
With each pass, the left portion of the array becomes increasingly sorted.
Case | Time Complexity |
---|---|
Best | O(n) |
Average | O(n²) |
Worst | O(n²) |
#include <iostream>
using namespace std;
void insertionSort(int arr[], int n) {
for (int i = 1; i < n; i++) {
int key = arr[i];
int j = i - 1;
// Shift larger elements to the right
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
// Print array after each pass
cout << "After pass " << i << ": ";
for (int k = 0; k < n; k++) {
cout << arr[k] << " ";
}
cout << endl;
}
}
void printArray(int arr[], int n) {
for (int i = 0; i < n; i++) {
cout << arr[i] << " ";
}
cout << endl;
}
int main() {
int arr[] = {12, 11, 13, 5, 6};
int n = sizeof(arr) / sizeof(arr[0]);
cout << "Original array:\n";
printArray(arr, n);
insertionSort(arr, n);
cout << "Sorted array:\n";
printArray(arr, n);
return 0;
}
Original array:
12 11 13 5 6
After pass 1: 11 12 13 5 6
After pass 2: 11 12 13 5 6
After pass 3: 5 11 12 13 6
After pass 4: 5 6 11 12 13
Sorted array:
5 6 11 12 13
Let’s sort:
[12, 11, 13, 5, 6]
[11, 12, 13, 5, 6]
[11, 12, 13, 5, 6]
[5, 11, 12, 13, 6]
[5, 6, 11, 12, 13]
[5, 6, 11, 12, 13]