CLRS:Insert sort in in c

时间:2024-08-03 19:32:50

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<time.h>
#define ARRAY_SIZE 1000
int buf[ARRAY_SIZE];
int main()
{
int i,j,n;
srand((unsigned int)time(0));
memset(buf,0,sizeof(buf[0]));
while(scanf("%d",&n)!=EOF)
{
for(i=1;i<=n;i++)buf[i]=rand()%100;//creat th data storage in buf
for(i=1;i<=n;i++)printf("%d ",buf[i]);//before sort
printf("\nAffter sort:\n");
for(j=2;j<=n;j++)
{
buf[0]=buf[j];
for(i=j-1;i>0&&buf[i]>buf[0];i--)buf[i+1]=buf[i];
buf[i+1]=buf[0];
}
for(i=1;i<=n;i++)printf("%d ",buf[i]);//after sort
printf("\n");
}

}