Insertion sort using C++ STL

C++Server Side ProgrammingProgramming

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 << '
'; } 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
raja
Updated on 01-Apr-2020 06:20:53

Advertisements