Insertion sort using C++ STL
Last Updated :
30 Aug, 2017
Implementation of Insertion Sort using STL functions.
Pre-requisites : Insertion Sort, std::rotate, std::upper_bound, C++ Iterators.
The idea is to use std::upper_bound to find an element making the array unsorted. Then we can rotate the unsorted part so that it ends up sorted. We can traverse the array doing these operations and the result will be a sorted array.
The code is offline on purpose to show hard-coded and easy to understand code.
#include <bits/stdc++.h>
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);
}
}
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);
}
|
Output:
1 2 3 4 5 5 6 7
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...