排序(完整可运行代码)

  • 格式:doc
  • 大小:16.50 KB
  • 文档页数:3

1)编写简单选择法函数
2)编写直接插入法函数
3)编写冒泡法排序函数
4)在主程序中输入一组数据元素(513,87,512,61,908,170,897,275,653,462),分别调用三种排序函数,输出每趟排序结果。

#include <stdio.h>
#define MAX 30
typedef int elemtype;
typedef int keytype;
void select_sort(elemtype list[],int n)
{
int i,j,k,small;
elemtype temp;
for(i=0;i<n;i++)
{
small=i;
for(j=i+1;j<n;j++)
{
if(list[small]>list[j])
small=j;
}
if(small != i)
{
temp=list[small];
list[small]=list[i];
list[i]=temp;
}
}
for(k=0;k<n;k++)
printf("%d ",list[k]);
printf("\n");
}
void linear_insert_sort(elemtype list[],int n)
{
int i,j,k,temp;
for(i=1;i<n;i++)
{
j=i-1;
temp=list[i];
while(temp<list[j] && j>=0)
{
j--;
}
list[j+1]=temp;
}
for(k=0;k<n;k++)
printf("%d ",list[k]);
printf("\n");
}
void bubble_sort(elemtype list[],int n)
{
int k,i;
elemtype temp;
int change=1;
int bound=n-1;
while(bound>0 && change == 1)
{
change=0;
for(i=0;i<bound;i++)
if(list[i]>list[i+1])
{
temp=list[i];
list[i]=list[i+1];
list[i+1]=temp;
change=1;
}
bound=bound-1;
}
for(k=0;k<n;k++)
printf("%d ",list[k]);
printf("\n");
}
int main()
{
elemtype list1[MAX],list2[MAX],list3[MAX];
int num;
printf("input the length of list[](<=%d):\n",MAX);
scanf("%d",&num);
printf("input the values of list[]:\n");
for(int i=0;i<num;i++)
{
scanf("%d",&list1[i]);
}
printf("select_sort:\n");
select_sort(list1,num);
printf("linear_insert_sort\n");
linear_insert_sort(list2,num);
printf("bubble_sort\n");
bubble_sort(list3,num);
return 0;
}。