Insertion sort using C++ STL



In this tutorial, we will be discussing a program to understand the insertion sort using C++ STL.

In this we use std::upper_bound to find the element at the wrong position, then rotate the unsorted part of the array to make it sorted.

Example

 Live Demo

#include <bits/stdc++.h> //function to perform insertion sort void insertionSort(std::vector<int> &vec){    for (auto it = vec.begin(); it != vec.end(); it++){       auto const insertion_point =       std::upper_bound(vec.begin(), it, *it);       std::rotate(insertion_point, it, it+1);    } } //printing the array void print(std::vector<int> vec){    for( int x : vec)    std::cout << x << " ";    std::cout << '\n'; } int main(){    std::vector<int> arr = {2, 1, 5, 3, 7, 5, 4, 6};    insertionSort(arr);    print(arr);    return 0; }

Output

1 2 3 4 5 5 6 7
Updated on: 2020-04-01T06:20:53+05:30

811 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements