//直接插入排序
#include <stdio.h>
#define MAXSIZE 100
typedef int KeyType;//关键码类型定义,假定为整型
typedef struct
{
KeyType key; //关键码定义
}ElemType;
typedef struct
{
ElemType elem[MAXSIZE];
int length;
}S_TBL;
//产生随机数
void Getsort(S_TBL *p)
{
int i;
srand((unsigned)time(NULL));
for(i=1;i<=p->length;i++)
p->elem[i].key=rand()%100;
}
//直接插入
void InsertSort(S_TBL *p)
{ int i,j;
for(i=2;i<=p->length;i++)
if(p->elem[i].key<p->elem[i-1].key)//小于时,需将elem[i]插入有序表
{
p->elem[0].key=p->elem[i].key;//为统一算法设置监测
for(j=i-1;p->elem[0].key<p->elem[j].key;j--)
p->elem[j+1]=p->elem[j];//记录后移
p->elem[j+1]=p->elem[0];//插入到正确位置
}
}
//输出
void Output(S_TBL *L)
{
int i;
for(i=1;i<=L->length;i++)
printf("%d\t",L->elem[i].key);
printf("\n");
}
main()
{ S_TBL s;
S_TBL *H;
int i,j;
KeyType y;
H=(S_TBL*)malloc(sizeof(S_TBL));
Getsort(H);
printf("原始数据为:\n");
Output(H);
InsertSort(H);
printf("插入后排序好的数据为:\n");
Output(H);
getch();
}