C++ Program For Insertion Sort
Last Updated :
07 Aug, 2023
Insertion sort is a simple sorting algorithm that works by dividing the array into two parts, sorted and unsorted part. In each iteration, the first element from the unsorted subarray is taken and it is placed at its correct position in the sorted array.
In this article, we will learn to write a C++ program to implement the Insertion sort algorithm.
Insertion Sort Algorithm in C++
- The first element of the array is assumed to be a sorted subarray.
- Start with the element at index 1 and store it in a variable key.
- Compare the current element key with the elements in the sorted subarray from right to left (elements at indices from j = i-1 to j = 0).
- Shift elements greater than the key one position to the right to make space for the current element until it finds a smaller element than the key and j is not zero.
- When the correct position for the key is found, it is inserted at arr[j + 1].
- Repeat these steps for the remaining elements of the unsorted subarray until the complete array is sorted.
Insertion Sort Program in C++
C++
#include <bits/stdc++.h>
using namespace std;
void insertionSort( int arr[], int n)
{
int i, key, j;
for (i = 1; i < n; i++) {
key = arr[i];
j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
void printArray( int arr[], int n)
{
int i;
for (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]);
insertionSort(arr, N);
printArray(arr, N);
return 0;
}
|
Complexity Analysis of Insertion Sort
Time Complexity
- Worst Case: O(n2)
- Best Case: O(n)
- Average Case: O(n2)
Auxiliary Space: O(1)
Working of Insertion Sort in C++
Below is the working of Insertion Sort with the help of a pictorial example:
Insertion Sort in C++
Please refer complete article on Insertion Sort for more details!
Related Articles
Share your thoughts in the comments
Please Login to comment...