插入排序就是每一步都将一个待排数据按其大小插入到已经排序的数据中的适当位置,直到全部插入完毕。
插入排序方法分直接插入排序和折半插入排序两种,这里只介绍直接插入排序。
#include <iostream>
using namespace std;
static void insert_sort(int unsorted[], int length)
{
for(int i=1; i<length; i++)
{
int key = unsorted[i];
int j = i - 1;
while(j >= 0 && unsorted[j] > key)
{
unsorted[j+1] = unsorted[j];
j=j-1;
}
unsorted[j+1] = key;
}
}
int main(void)
{
int x[6] = {5,2,4,6,1,3};
insert_sort(x, 6);
for(int i=0; i<6; i++)
{
cout << x[i] << " ";
}
cout << endl;
getchar();
return 0;
}
原文:http://www.cnblogs.com/bwin/p/5292738.html