发个直接插入排序的代码,刚学C语言请指正
#include<stdio.h>#define M 10
int arry[M]={0,41,48,23,56,78,90,23,56,67};
int sort(int a,int b);
void display(int a[M]);
int main(void)
{
printf("显示当前数据\n");
display(arry);
for(int i=2;i<=M-1;i++)
{
if(sort(arry[i],arry[i-1]))
{
arry[0]=arry[i];
arry[i]=arry[i-1];
//for(int j=i-2; ;j--)
int j=i-2;
while (sort(arry[0],arry[j]))
{
arry[j+1]=arry[j];
j--;
}
arry[j+1]=arry[0];
}
}
printf("显示排序后的数据:\n");
display(arry);
return 0;
}
int sort(int a,int b)
{
if(a<b)
return 1;
else
return 0;
}
void display(int a[M])
{
for (int i=1;i<=M;i++)
printf("%-4d",arry[i]);
printf("\n");
}
折半插入排序代码如下:
#include<stdio.h>
#define M 10
int arry[M]={0,41,48,23,56,78,90,23,56,67};
int sort(int a,int b);
void display(int a[M]);
int main(void )
{
printf("显示当前数据\n");
display(arry);
for (int i=2;i<=M-1;i++)
{
arry[0]=arry[i];
int low=1;
int high=i-1;
while (low<=high)
{
int m=(low+high)/2;
if(sort(arry[0],arry[m]))
high=m-1;
else
low=m+1;
}
for(int j=i-1;j>=high+1;--j)
arry[j+1]=arry[j];
arry[high+1]=arry[0];
}
printf("显示排序后的数据:\n");
display(arry);
return 0;
}
int sort(int a,int b)
{
if(a<b)
return 1;
else
return 0;
}
void display(int a[M])
{
for (int i=1;i<=M-1;i++)
printf("%-4d",arry[i]);
printf("\n");
}