c - 具有结构的字符串的冒泡排序

标签 c

我尝试对与结构和数组有关的字符串使用冒泡排序。基本上我想比较我按字母顺序排列的每本书的标题。谁能告诉我我做错了什么?

struct Book
{
    /* Book details */
    char title[MAX_TITLE_LENGTH+1];   
    char author[MAX_AUTHOR_LENGTH+1]; 
    int  year;                        
};
void menu_print_database(void)
{
    char temp[MAX_AUTHOR_LENGTH+1];
    char title[no_books][MAX_TITLE_LENGTH+1];
    int i,sorted,swaps=0;
    int no_books;

    do
    {
        for (i=0; i<no_books; i++)
        {   
            if (strcmp(title[i-1], title[i]) > 0)
            {
                sorted=0;
                strcpy(temp, title[i+1]);
                strcpy(title[i-1], title[i]);
                strcpy(title[i], temp);
                swaps++;
            }   
        }
    } while (!sorted);

    for (i=0;i<no_books;i++){
        printf("Title: %s\n",book_array[i].title);
        printf("Author: %s\n",book_array[i].author);
        printf("Year: %d\n",book_array[i].year);
    }
}

最佳答案

1) title 的内容未设置,但我想您只跳过了这部分代码...另外,char title[no_books][MAX_TITLE_LENGTH+ 1]; 使用名为 no_books 的变量,该变量仅在稍后定义。

2) 在这里,当 i==0 时,您尝试访问 title[-1]:

for (i=0; i<no_books; i++)
{   
    if (strcmp(title[i-1], title[i]) > 0)

3) sorted 应在 for 循环之前设置为 1(您假设数组已排序,如果您在 if 语句中输入,则将 sorted 设置为0)。

4) 交换不正确:strcpy(temp, title[i+1]) 应该是 strcpy(temp, title[i-1])

关于c - 具有结构的字符串的冒泡排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50219306/

相关文章:

c - 如何在 C 中声明一个条目数量未知的数组?

无法使用 MinGW 编译 C 代码

c - 'stray\223 and\224 error' 和 C 中的其他错误

c - 函数 poll 的头文件

c - 总结一个中心点周围的所有点?

c++ - C/C++ 使用 int 或 unsigned int

c - 为什么我不能溢出全局变量?

c - Turbo C 中的 SHA256 算法无法编译

c - gcc 编译多个文件

c - 打印 char 数组末尾的意外输出