简体   繁体   English

作业的冒泡排序代码无法按预期工作

[英]Buble sort code for homework doesn't work as expected

I have task to make a program that can sort names.我的任务是制作一个可以对名称进行排序的程序。

The output of the program:程序的输出:

How many names will be inputed? 3
Angelia Kho
Angel
Angelina

Sorted Names(Ascending):
1. Angel
2. Angelia Kho
3. Angelina

This is my code:这是我的代码:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

int main()
{
    int a;
    char ignore;
    
    printf("How Many names will be inputed? ");
    scanf("%d", &a);
    
    scanf("%c", &ignore);
    
    char names [a][255];
    char temp [255];
    
    int j;
    for(j = 0; j < a; j++){
        scanf("%[^\n]", names[j]);
        scanf("%c", &ignore);
    }
    
    int i;
    
    for(i = 0; i<a; i++)
    {
        for(j = i; j<a; j++)
        {
            if(strcmp(names[i], names[j]> 0))
            {
                strcpy(temp, names[i]);
                strcpy(names[i], names[j]);
                strcpy(names[j],temp);
            }
        }
    }
    
    printf("\nsorted names(Ascending): \n");
    for(i = 0; i < a; i++)
    {
        printf("%d. %[^\n]", i, names[i]);
    }
}

The error is:错误是:

[Warning]passing argument 2 of 'strcmp' makes pointer from integer without cast

But, it still working until user input但是,它仍然有效,直到用户输入

Output for now:现在输出:

How Many names will be inputed? 3
Angelia Kho
Angel
Angelina

--------------------------------
Process exited after 23.08 seconds with return value 3221225477
Press any key to continue...

For starters calls like this对于像这样的初学者电话

scanf("%c", &ignore);

are redundant.是多余的。 You may remove them and change the call of scanf for entering strings the following way您可以删除它们并更改 scanf 的调用以通过以下方式输入字符串

scanf( " %254[^\n]", names[j] );
       ^^^

Pay attention to the leading space in the format string.注意格式字符串中的前导空格。 It allows to skip white space characters as for example the new line character '\n' stored in the input buffer after a preceding call of scanf .它允许跳过空白字符,例如在前面调用scanf之后存储在输入缓冲区中的换行符'\n'

In the if statement在 if 语句中

if(strcmp(names[i], names[j]> 0))

there is a typo.有一个错字。 The expression names[j] > 0 has the type int and is equal to 1.表达式names[j] > 0具有int类型并且等于 1。

You have to write你必须写

if(strcmp(names[i], names[j] ) > 0 )

Another typo in this call of printf这个printf调用中的另一个错字

printf("%d. %[^\n]", i, names[i]);

Rewrote it like像这样改写

printf("%d. %s\n", i, names[i]);

Also the used method of sorting is not the bubble sort method.此外,使用的排序方法不是冒泡排序方法。 It looks like the selection sort method with redundant swaps.它看起来像带有冗余交换的选择排序方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM