Trong hướng dẫn này, chúng ta sẽ thảo luận về một chương trình để hiểu cách sắp xếp chèn bằng cách sử dụng C ++ STL.
Trong phần này, chúng tôi sử dụng std ::upper_bound để tìm phần tử ở vị trí sai, sau đó xoay phần chưa được sắp xếp của mảng để làm cho nó được sắp xếp.
Ví dụ
#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;
} Đầu ra
1 2 3 4 5 5 6 7