Open In App

C++ Program For Insertion Sort

Last Updated : 07 Aug, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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++




// C++ program for insertion sort
#include <bits/stdc++.h>
using namespace std;
 
// Function to sort an array
// using insertion sort
void insertionSort(int arr[], int n)
{
    int i, key, j;
    for (i = 1; i < n; i++) {
        key = arr[i];
        j = i - 1;
 
        // Move elements of arr[0..i-1],
        // that are greater than key, to one
        // position ahead of their
        // current position
        while (j >= 0 && arr[j] > key) {
            arr[j + 1] = arr[j];
            j = j - 1;
        }
        arr[j + 1] = key;
    }
}
 
// A utility function to print
// an array of size n
void printArray(int arr[], int n)
{
    int i;
    for (i = 0; i < n; i++)
        cout << arr[i] << " ";
    cout << endl;
}
 
// Driver code
int main()
{
    int arr[] = { 12, 11, 13, 5, 6 };
    int N = sizeof(arr) / sizeof(arr[0]);
 
    insertionSort(arr, N);
    printArray(arr, N);
 
    return 0;
}
// This is code is contributed by rathbhupendra


Output

5 6 11 12 13 

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++

Insertion Sort in C++

 

Please refer complete article on Insertion Sort for more details!

Related Articles



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads