Insertion Sort in C++
Insertion Sort Algorithm in C++ (Complete Implementation).
1#include <iostream>2using namespace std;34void insertionSort(int arr[], int n) {5 for (int i = 1; i < n; i++) {6 int key = arr[i];7 int j = i - 1;89 // Move elements greater than key one position ahead10 while (j >= 0 && arr[j] > key) {11 arr[j + 1] = arr[j];12 j--;13 }14 arr[j + 1] = key;15 }16}1718void printArray(int arr[], int n) {19 for (int i = 0; i < n; i++) {20 cout << arr[i] << " ";21 }22 cout << endl;23}2425int main() {26 int arr[] = {64, 34, 25, 12, 22, 11, 90};27 int n = sizeof(arr) / sizeof(arr[0]);2829 cout << "Original array: ";30 printArray(arr, n);3132 insertionSort(arr, n);3334 cout << "Sorted array: ";35 printArray(arr, n);3637 return 0;38}
Output
Original array: 64 34 25 12 22 11 90 Sorted array: 11 12 22 25 34 64 90
What's going on
The program sorts an array of integers using the Insertion Sort algorithm. For example:
Insertion Sort builds the sorted array incrementally by inserting each element into its correct position in the already sorted portion.
Header File Used
This header provides:
1#include <iostream>
Understanding Insertion Sort
Algorithm Concept
:
Visual Example
:
Initial: [64, 34, 25, 12, 22, 11, 90]
Step 1: [34, 64, 25, 12, 22, 11, 90] (insert 34 before 64)
Step 2: [25, 34, 64, 12, 22, 11, 90] (insert 25 at beginning)
Step 3: [12, 25, 34, 64, 22, 11, 90] (insert 12 at beginning)
Step 4: [12, 22, 25, 34, 64, 11, 90] (insert 22 after 12)
Step 5: [11, 12, 22, 25, 34, 64, 90] (insert 11 at beginning)
Step 6: [11, 12, 22, 25, 34, 64, 90] (90 already in place)
Function: insertionSort()
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;
}
}
How it works
:
Step-by-Step Algorithm
For each element arr[i] (starting from i=1)
:
Step 1: Store Current Element
Step 2: Find Insertion Position
Step 3: Insert Element
Example
(inserting 22 when sorted portion is [12, 25, 34, 64]):
Understanding the Inner While Loop
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
How it works
:
Why j >= 0?
:
Time and Space Complexity
Time Complexity
:
Space Complexity
: O(1)
Stability
: Stable
When to Use Insertion Sort
Best For
:
Not Recommended For
:
Important Considerations
Starting Index
:
Shifting Elements
:
Key Variable
:
return 0;
This ends the program successfully.