步骤
1 元素从1开始遍历到末尾
2 把当前元素和前面的元素逐一比较,比它大的就往后移一位(因为前面都是排好序的,所以不会造成错误)
3 当前面的元素到了不比它大的时候,就放在该位置
voidinsertionSort(vector<int> &v)
{
for(int i = 1; i < v.size(); ++i) //对每个元素进行排序操作
{
int j;
int key = v[i];
for(j = i - 1; j >= 0 &&v[j] > key;--j) //跟前面的每一个元素比较
v[j+1] = v[j]; //
v[j+1] = key; //因为j已经减过了
}
}
#include<vector>
using namespace std;
voidinsertionSort(vector<int> &v)
{
int i,j;
int temp;
for(i=1;i<v.size();i++)
{
temp = v[i]; //store the original sorted array in temp
for(j=i ; j>0 && temp <v[j-1] ; j--) //compare the new array with temp(maybe -1?)
{
v[j]=v[j-1]; //all larger elements are moved one pot to theright
}
v[j]=temp; //´ËʱµÄjÒѾÊÇ¿ÕλµÄj
}
}
}
经典排序算法 – 插入排序Insertion sort
插入排序就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕。
插入排序方法分直接插入排序和折半插入排序两种,这里只介绍直接插入排序,折半插入排序留到“查找”内容中进行。
图1演示了对4个元素进行直接插入排序的过程,共需要(a),(b),(c)三次插入。