插入排序(Insertion Sort)是一种玩扑克的时候用的方法,我们摸牌时已经抽到的牌我们已经排好序了,抽上来一张新牌,我们一般不会直接放在最后,等全部抽完之后再进行排序,而是抽上来之后立刻放到对应的位置。
可以看GIF图了
抽牌的顺序就是 6 5 3 1 8 7 2 4
这里需要注意的操作是如何做到将新插入的记录放到它应该待的地方,而保证放好后序列依旧是有序的?
以3为例,当检测到它之前的元素大于它时,就依次向后移位。
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void InsertSort(vector<int> & s);
void Show(int x);
int main()
{
using namespace std;
vector<int> input = { 40, 8, 15, 18, 12 };
InsertSort(input);
for_each(input.begin(), input.end(), Show);
cin.get();
return 0;
}
void InsertSort(vector<int> & s)
{
for (int i = 1; i < s.size(); i++)
{
int j = i;
int temp = s[j];
while (j-1>= 0 && s[j - 1]>temp) //位置还未找到时
{ //循环移位
s[j] = s[j - 1];
j--;
}
s[j] = temp;
}
}
void Show(int x)
{
cout << x << " ";
}