编写一个程序,要求生成一组随机数,根据输入不同指令调用相应的排序算法实现对它的顺序排序
预处理指令:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 20
1-插入排序:
void insert_sort(int aa[])/*插入排序*/
{
int i,j,temp;
for(i=1;i<N;i++)/*从第二个元素开始*/
{
temp=aa[i];
for(j=i-1;j>=0&&aa[j]>temp;j--)/*找到插入位置*/
aa[j+1]=aa[j];/*往后移位*/
aa[j+1]=temp;/*插入*/
}
}
2-选择排序:
void select_sort(int aa[])/*选择排序*/
{
int i,j,temp1,temp2;
for(i=0;i<N-1;i++)
{
temp1=i;
for(j=i;j<N;++j)/*找出最小值下标并存入临时变量temp1*/
if(aa[temp1]>aa[j])
temp1=j;
if(temp1!=i)/*交换*/
{
temp2=aa[i];
aa[i]=aa[temp1];
aa[temp1]=temp2;
}
}
}
3-冒泡排序:
void bubble_sort(int aa[])/*冒泡排序*/
{
int i,j,temp;
for(i=1;i<=N-1;i++)/*冒泡次数N-1次*/
for(j=0;j<N-i;j++)/*单次冒泡*/
if(aa[j]>aa[j+1])
{
temp=aa[j];
aa[j]=aa[j+1];
aa[j+1]=temp;
}
}
4-快速排序:
void quick_sort(int aa[],int low,int high)/*快速排序(冒泡排序的全新升级版)*/
{
int i=low,j=high;
int key;/*定义一个存放关键数的变量*/
if(low<high)
{
key=aa[low];
while(low<high)/*单次快速排序*/
{
for(;low<high&&aa[high]>key;high--);/*从后往前搜索找到第一个小于key的数*/
if(low<high)
{
aa[low]=aa[high];
low++;
}
for(;low<high&&aa[low]<key;low++);/*从前往后搜索找到第一个大于key的数*/
if(low<high)
{
aa[high]=aa[low];
high--;
}
}
aa[low]=key;
quick_sort(aa,i,low-1);
quick_sort(aa,low+1,j);
}
}
5-希尔排序:
void shell_sort(int aa[])/*希尔排序(插入排序的全新升级版)*/
{
int d,i,j,temp;
for(d=N/2;d>0;d/=2)/*控制增量的改变*/
for(i=d;i<N;i++)/*控制即将要插入的元素的改变*/
{
temp=aa[i];/*保存插入元素的值*/
for(j=i-d;aa[j]>temp&&j>=0;j-=d)/*找出插入位置*/
aa[j+d]=aa[j];
aa[j+d]=temp;/*插入*/
}
}
调用排序函数进行排序:
void select_to_call(int aa[],char g1)/*根据输入的字符调用相应的排序函数*/
{
if(g1=='i')
insert_sort(aa);
if(g1=='s')
select_sort(aa);
if(g1=='b')
bubble_sort(aa);
if(g1=='q')
quick_sort(aa,0,N-1);
if(g1=='l')
shell_sort(aa);
}
下面是入口函数:
void main()
{
int aa[N],i;
char g,t,h;
srand((unsigned)(time(NULL)));/*播种*/
do
{
printf("Randomly generate %d integer:\n",N);
for(i=0;i<N;i++)/*生成一组随机数*/
{
aa[i]=rand()%99+1;
printf("%d ",aa[i]);
}
printf("\n");
printf("Input a character from i,s,b,q,l:");
scanf("%c",&g);
while(!(g=='i'||g=='s'||g=='b'||g=='q'||g=='l'))
{
printf("Wrong input!Please input again:");
while((h=getchar())!='\n'&&h!=EOF);/*清空输入流缓存区数据*/
scanf("%c",&g);
}
printf("the sort results are as follows:\n");
select_to_call(aa,g);
for(i=0;i<N;i++)
printf("%d ",aa[i]);
printf("\n\n");
printf("input \"Y\" to continue next sort,otherwise exit:");
while((h=getchar())!='\n'&&h!=EOF);
t=getchar();
while((h=getchar())!='\n'&&h!=EOF);
}while(t=='Y');
}