Insertion sort using C++ STL

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.





// C++ program to implement insertion sort using STL.
#include <bits/stdc++.h>
// Function to sort the array
void insertionSort(std::vector<int> &vec)
    for (auto it = vec.begin(); it != vec.end(); it++)
        // Searching the upper bound, i.e., first 
        // element greater than *it from beginning
        auto const insertion_point = 
                std::upper_bound(vec.begin(), it, *it);
        // Shifting the unsorted part
        std::rotate(insertion_point, it, it+1);        
// Function to print the array
void print(std::vector<int> vec)
    for( int x : vec)
        std::cout << x << " ";
    std::cout << '\n';
// Driver code
int main()
    std::vector<int> arr = {2, 1, 5, 3, 7, 5, 4, 6};    



1 2 3 4 5 5 6 7

This article is contributed by Rohit Thapliyal. If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

GeeksforGeeks has prepared a complete interview preparation course with premium videos, theory, practice problems, TA support and many more features. Please refer Placement 100 for details

My Personal Notes arrow_drop_up
Article Tags :
Practice Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.