使用 C++ STL 的插入排序
在本教程中,我們將討論一個使用 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP