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

2024-12-02 19:07:11
推荐回答(1个)
回答1:

#include
#include
#include
#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;ifor(j=i+1;jif(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{gets(s[i]);
p[i]=s[i];
}
sort(p);
printf("\nThe sequence after sort is:\n");
for(i=0;iprintf("%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