ในบทช่วยสอนนี้ เราจะพูดถึงโปรแกรมเพื่อทำความเข้าใจการเรียงลำดับการแทรกโดยใช้ C++ STL
ในที่นี้ เราใช้ std::upper_bound เพื่อค้นหาองค์ประกอบในตำแหน่งที่ไม่ถูกต้อง จากนั้นหมุนส่วนที่ไม่ได้จัดเรียงของอาร์เรย์เพื่อทำการจัดเรียง
ตัวอย่าง
#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;
} ผลลัพธ์
1 2 3 4 5 5 6 7