#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
void insertsort(vector<int>&array) {
int i, j, temp;
for ( i = 1; i < array.size(); i++) {
temp = array[i];
// 手里面已经有的元素为array[j-1] 当其大于要插入的元素temp时。 array[j] =array[j-1]
// 要不断将所有大于temp的元素后移 此时找到小于temp或者为0,就是插入的位置
for ( j = i; j > 0 && array[j - 1] > temp; j--)
array[j] = array[j - 1];
array[j] = temp;
}
}
int main() {
vector<int> array{2,1,3,4,5,6};//定义一个vector数组array
insertsort(array);
for (auto x : array) {
cout << x << ' ';
}
system("pause");
return 0;
}
简单排序之插入排序
最新推荐文章于 2024-07-15 22:10:26 发布