排序算法之插入排序

来源:互联网 发布:windows文件系统书籍 编辑:程序博客网 时间:2024/06/14 11:09
/*======================================================================================插入排序:对于 0 到 N-1 之间的每一个 i,将 a[i] 与 a[0] 到 a[i-1] 中比它小的所有元素依次有序地交换。在索引i由左向右变化的过程中,它左侧的元素总是有序的,所以当i到达数组的右端时排序就完成了。========================================================================================最差时间分析:O(n2)     平均时间复杂度:O(n2)     稳定度:稳定     空间复杂度:O(1) ======================================================================================*/#include<iostream>#include<vector>using namespace std;// 互换两个参数的值template <typename T> // 函数模板 以适应各种类型void exch(T &a, T &b) {  T i = a;a = b;b = i;}// 互换两个参数的值template <typename T> // 函数模板 以适应各种类型void exch(vector<T>&arr, const int a,const int b) { T i = arr[a];arr[a] = arr[b];arr[b] = i;}/*插入排序*/template <typename T>// 函数模板 以适应各种类型void sort_Insertion(vector<T>&a) {int n = a.size();                    for (int i = 1; i < n; i++) {  // 将 a[i] 插入到 a[i-1]、a[i-2]、a[i-3]...之中          for (int j = i; j > 0 && a[j]< a[j-1]; j--)exch(a, j, j - 1);}}int main() {vector<int>arr = { 1,3,5,1455,75,225,995,2,233,58,899,55 };sort_Insertion(arr);for (int i = 0; i < arr.size(); i++) {cout << arr[i] << " ";}/*for (auto &i : arr) {  // 自动查看arr数组类型,每个循环i自动+1 ,i绑定 arr[i]cout << i << " ";}*/cout << "\n";system("pause");  //暂停以显示return 0;}