马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
从键盘上输入5个字符串,对其进行升序排序并输出,不能使用strcmp函数,求大佬帮忙看看,这到底哪错了,排序结果就是不正确
#include<stdio.h>
#include<string.h>
#define MAX_LINE 5
#define MAX_LINE_LEN 81
void sortP_Str(char *pstr[]);
int Find(char a[],char b[]);
int main(void)
{
int i;
char *pstr[MAX_LINE], str[MAX_LINE][MAX_LINE_LEN];
for (i=0; i<MAX_LINE; i++)
{
pstr[i] = str[i];
}
printf("Input 5 strings:\n");
for (i=0; i<MAX_LINE; i++)
{
gets(pstr[i]);
}
sortP_Str(pstr);
printf("---------------------------\n");
for (i=0; i<MAX_LINE; i++)
{
printf("%s\n", pstr[i]);
}
return 0;
}
void sortP_Str(char *pstr[])
{
int i, j;
char *p;
for (i=0; i<3; i++)
{
for (j=i; j<=3; j++)
{
if (Find(pstr[i],pstr[j]))
{
p = *(pstr+i);
*(pstr+i) = *(pstr+j);
*(pstr+j) = p;
}
}
}
}
int Find(char a[],char b[])
{
int i = 0, j = 0;
int ret = 0;
while ((i<strlen(a))||(j<strlen(b)))
{
if (a[i]> b[j])
{
ret = a[i] - b[j];
}
else if (a[i]< b[j])
{
ret = a[i] - b[j];
}
else;
i++, j++;
}
return ret;
}
示例是这样的:
Input 5 strings:
hello
My
Friend
are you ready?
help me!
---------------------------
Friend
My
are you ready?
hello
help me!
本帖最后由 jackz007 于 2020-3-14 16:41 编辑
- #include<stdio.h>
- #define MAX_LINE 5
- #define MAX_LINE_LEN 81
- compare(char * s1 , char * s2)
- {
- int k , r ;
- for(k = 0 , r = s1[k] - s2[k] ; s1[k] && s2[k] && ! r ; k ++ , r = s1[k] - s2[k]) ;
- return r ;
- }
- void sortstr(char str[][MAX_LINE_LEN])
- {
- char s[MAX_LINE_LEN] ;
- int d , i , j , k ;
- for(i = i ; i < MAX_LINE ; i ++) {
- for(j = i ; j > 0 && compare(str[j - 1] , str[j]) > 0 ; j --) {
- for(d = 0 , s[d] = str[j - 1][d] ; s[d] ; d ++ , s[d] = str[j - 1][d]) ;
- for(d = 0 , str[j - 1][d] = str[j][d] ; str[j - 1][d] ; d ++ , str[j - 1][d] = str[j][d]) ;
- for(d = 0 , str[j][d] = s[d] ; str[j][d] ; d ++ , str[j][d] = s[d]) ;
- }
- }
- }
- main(void)
- {
- char c , s[MAX_LINE][MAX_LINE_LEN] ;
- int i , j , k ;
- for(i = 0 ; i < MAX_LINE ; i ++) for(j = 0 ; (c = getchar()) != '\n' ; s[i][j ++] = c , s[i][j] = '\0') ;
- sortstr(s) ;
- printf("\n****************************************\n\n") ;
- for(i = 0 ; i < MAX_LINE ; i ++) printf("%s\n" , s[i]) ;
- }
复制代码
编译、运行实况:
- C:\Bin>g++ -o ss ss.c
- C:\Bin>ss
- hello
- My
- Friend
- are you ready?
- help me!
- ****************************************
- Friend
- My
- are you ready?
- hello
- help me!
- C:\Bin>
复制代码
|