算法思想:从一组数据中的第二位开始,与前面的数依此比较,若前面的数大于当前要插入的数,则把大于的数后移一位,再于下一位数比较,重复操作,直到最后一位。
代码如下:
#include<iostream>
#include<string>
#include<vector>
using namespace std;
//插入排序
void InsertSort(vector<int>&a)
{
for (int i = 1; i < a.size(); i++)
{
//记录要插入的值
int k = a[i];
int j = i - 1;
while (j >= 0 && a[j] > k)
{
//后移
a[j + 1] = a[j];
j--;
}
//插入值
a[j + 1] = k;
}
}
int main()
{
vector<int>a = { 9,3,6,7,8,1,2,5,4,0 };
cout << "排序前:" << endl;
//迭代器访问遍历
for (vector<int>::iterator i=a.begin();i!=a.end();i++)
{
cout << (*i) << " ";
}
cout << endl;
cout << "排序后:" << endl;
InsertSort(a);
for (auto x:a)//把a中的值一个一个赋值给x
{
cout << x <<" ";
}
cout << endl;
system("pause");
return 0;
}