 
  Data Structure Data Structure
 Networking Networking
 RDBMS RDBMS
 Operating System Operating System
 Java Java
 MS Excel MS Excel
 iOS iOS
 HTML HTML
 CSS CSS
 Android Android
 Python Python
 C Programming C Programming
 C++ C++
 C# C#
 MongoDB MongoDB
 MySQL MySQL
 Javascript Javascript
 PHP PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
#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
Advertisements
 