在本教程中,我们将讨论一个程序,以了解使用C ++ STL的插入排序。
在这种情况下,我们使用std::upper_bound在错误的位置查找元素,然后旋转数组的未排序部分以使其排序。
#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);
return 0;
}输出结果
1 2 3 4 5 5 6 7