插入排序用数组模拟如上,首先确定要排的为升序还是降序,然后找到每个元素要插入的位置,从第二个元素开始插入,找到位置后将该元素插入,从插入的位置到该元素原来的位置中间的元素均向后移动一个位置。依次循环。
#include <iostream>
#include <stdio.h>
#include <string.h>
using namespace std;
int main()
{
int i,j,tem;
int length;
int a[]={2,43,24,19,25,39,11,6,5};
// length = a.length();
length = sizeof(a)/sizeof(int);
cout<<length<<endl;
printf("Before ordered:\n");
for(i = 0; i < length; i++)
printf("%d ",*(a+i));
printf("\n\n");
for(i = 1; i < length; i++)
{
j = i-1;
tem = a[i];
while(j>=0 && a[j]>tem)
{
a[j+1] = a[j];
j--;
}
a[j+1] = tem;
}
printf("After ordered:\n");
for(i = 0; i < length; i++)
printf("%d ",*(a+i));
printf("\n");
return 0;
}