使用C ++ STL进行插入排序
在本教程中,我们将讨论一个程序,以了解使用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
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短