输入五个国家的名称并按字母顺序排列输出

bwz290845851 2009-05-29 05:02:32
#include"stdio.h"
#include"string.h"
main()
{
char st[20],cs[5][20];
int i,j,p;
printf("input country'name:\n");
for(i=0;i<5;i++)
gets(cs[i]);
printf("\n");
for(i=0;i<5;i++)
puts(cs[i]);

for(i=0;i<5;i++)
{
p=i;strcpy(st,cs[i]);
for(j=j+1;j<5;j++)
if(strcmp(cs[j],st)<0)
{
p=j;strcpy(st,cs[j]);
}
if(p!=i)
{
strcpy(st,cs[i]);
strcpy(cs[i],cs[p]);
strcpy(cs[p],st);
}
puts(cs[i]);
}

printf("\n");

}
怎么排列不出来啊 我快疯了
...全文
2119 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
nosxcy 2009-05-29
  • 打赏
  • 举报
回复
给你个示例做比较,交换指针来进行数组排序可能比你的方法要好些.

/* sort_str.c -- reads in strings and sorts them */

#include <stdio.h>

#include <string.h>

#define SIZE 81 /* string length limit, including \0 */

#define LIM 20 /* maximum number of lines to be read */

#define HALT "" /* null string to stop input */

void stsrt(char *strings[], int num);/* string-sort function */



int main(void)

{

char input[LIM][SIZE]; /* array to store input */

char *ptstr[LIM]; /* array of pointer variables */

int ct = 0; /* input count */

int k; /* output count */



printf("Input up to %d lines, and I will sort them.\n",LIM);

printf("To stop, press the Enter key at a line's start.\n");

while (ct < LIM && gets(input[ct]) != NULL

&& input[ct][0] != '\0')

{

ptstr[ct] = input[ct]; /* set ptrs to strings */

ct++;

}

stsrt(ptstr, ct); /* string sorter */

puts("\nHere's the sorted list:\n");

for (k = 0; k < ct; k++)

puts(ptstr[k]) ; /* sorted pointers */



return 0;

}



/* string-pointer-sorting function */

void stsrt(char *strings[], int num)

{

char *temp;

int top, seek;



for (top = 0; top < num-1; top++)

for (seek = top + 1; seek < num; seek++)

if (strcmp(strings[top],strings[seek]) > 0)

{

temp = strings[top];

strings[top] = strings[seek];

strings[seek] = temp;

}

}
liao05050075 2009-05-29
  • 打赏
  • 举报
回复

#include"stdio.h"
#include"string.h"
main()
{
char st[20],cs[5][20];
int i,j,p;
printf("input country'name:\n");
for(i=0;i <5;i++)
gets(cs[i]);
printf("\n");
for(i=0;i <5;i++)
puts(cs[i]);

for(i=0;i <5;i++)
{
p=i;
strcpy(st,cs[i]);
for(j=j+1;j <5;j++) //这一句改成j=i+1
if(strcmp(cs[j],st) <0)
{
p=j;strcpy(st,cs[j]);
}
if(p!=i)
{
strcpy(st,cs[i]);
strcpy(cs[i],cs[p]);
strcpy(cs[p],st);
}
puts(cs[i]);
}

printf("\n");

}

69,371

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧