插入排序的基本思想是,针对每一个待排序数字,从它前一个位置的数起,依次比较,找到合适的位置插入,后面的数字顺序后移。实现比较简单
/**-----------------------------------------
houyong
---------------------------------------------*/
#include <iostream>
using namespace std;
void Insertion_Sort(int A[], int n)
{
int i, j;
for(j=1; j<n; j++)
{
int key = A[j];
i = j - 1;
while(i>=0&&A[i]>key)
{
A[i+1] = A[i];
i = i - 1;
}
A[i+1] = key;
}
}
int main()
{
int A[] = {4, 5, 7, 9, 3, 2, 6, 1, 11, 10};
for(int i = 0; i<10; i++)
cout<<A[i]<<" ";
cout<<endl;
Insertion_Sort(A, 10);
for(int i = 0; i<10; i++)
cout<<A[i]<<" ";
cout<<endl;
return 0;
}
/**
4 5 7 9 3 2 6 1 11 10
1 2 3 4 5 6 7 9 10 11
*/