c语言: 输入10个字符串,用选择排序法对十个字符串按大到小排序并输出

如题所述

#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
#define N 10/* 设定要输入的字符串个数,可更改 */

int cmp(char *p1,char *p2) /* 字符串比较函数 */
{int i=0;
while (*(p1+i)==*(p2+i))
if (*(p1+i++)=='\0') return 0; /* 这里是先判断*(p1+i)=='\0',然后再是i++ */
return (*(p1+i)-*(p2+i));
}

void sort(char *a[N]) /*排序函数*/
{char *temp;
int i,j;
for(i=0;i<N-1;i++)/* 选择排序 */
for(j=i+1;j<N;j++)
if(cmp(a[i],a[j])<0)
{temp=a[i];/* 交换的是字符串的地址,不是字符串的内容,可更改 */
a[i]=a[j];
a[j]=temp;
}
}
int main(void )
{int i;
char s[N][81],*p[N];/* 设定每个字符串不超过80字节 */
printf("Please input %d strings one by one:\n",N);
for(i=0;i<N;i++)
{gets(s[i]);
p[i]=s[i];
}
sort(p);
printf("\nThe sequence after sort is:\n");
for(i=0;i<N;i++)
printf("%s\n",p[i]);
getch();
return 0;
}

运行结果:
Please input 10 strings one by one:
asdf
dfggf
jkhl
uiop
ghjk
aaaa
vnbmkgh
bbbb
dgfjyt
cccc

The sequence after sort is:
vnbmkgh
uiop
jkhl
ghjk
dgfjyt
dfggf
cccc
bbbb
asdf
aaaa
温馨提示:答案为网友推荐,仅供参考
相似回答