在C中对结构元素进行排序

谢尔盖·列瓦绍夫(Sergei Levashov)

我有以下代码,在其中必须按字母顺序对书名进行排序。这是我的代码,不确定如何执行实际排序。由于会提示用户输入多达30本书,因此也将不胜感激有关如何对多于2本书进行分类的任何帮助。

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

struct Books
{
    char title[256];
    char author[256];
    char genre[256];
    int qualityRATE;
    int pages;
};

int numberbook = 1;
int casee;
int booksnumber;
int i;

int main()
{
    char again;

    do
    {
        printf("how many books will you be entering today?");
        scanf("%i", &booksnumber);
        printf("Enter the information for your book.\n Name\n Author\n Genre\n quality rating\n\n");
        struct Books book1;
        struct Books book2;
        scanf("%s", book1.title);
        scanf("%s", book2.title);

        printf("The title of book %i is: %s\n", numberbook, book1.title);
        printf("The title of book %i is: %s\n", numberbook, book2.title);

        printf("how would you like to sort?\n 1: By title\n 2: by Author\n 3: by pages\n\n");
        scanf("%i", &casee);
        switch(casee) 
        {
            case 1:
                for(i = 1; i < booksnumber, i++;)
                {
                    if(strcmp(book[i].title, book[i+1].title) < 0)
                        strcpy(book[i+1].title, book[i].title);
                    else
                        if(strcmp(book[i+1].title, book[i].title) < 0)
                            strcpy(book[i].title, book[i+1].title);

                }
                printf("\n%s\n", book1.title);
                break;
            case 2:
                break;
        }

        printf("Another book?\n");
        numberbook++;
        scanf("%s", &again);
    }

    while(again == 'y');
    return 0;
}
乔·布莱克爵士

我在您的代码中看到了一些问题:

您必须初始化一本书结构的数组,而不是book1和book2,声明:

struct books book[nnn] /* where nnn is the maximum number of book */

您必须使用从0开始进入do while循环的计数器(应为booknumber)

您必须使用book [booksnumber]使用scanf,并为每个scanf递增booknumber。

如果您想要一个可靠的排序引擎,建议您使用qsort函数(qsort是stdlib.h中的C库函数)

参见:www.cplusplus.com/reference/cstdlib/qsort

对项目进行排序的正确方法应该是以下代码:

struct Books app;
int i,j;

for(i=0;i<booksnumber;i++) {
       for(j=i+1;j<booksnumber;j++) {
          if (strcmp(book[i].title,book[j].title)<0) {
             app=book[i];
             book[j]=book[i];
             book[i]=app;
          }
       }
    }

我认为第一个for循环应如下所示更好,但我已经在运行中编写了此代码,但随后没有验证其行为。

for(i=0;i<booksnumber-1;i++)

我还没有验证排序的方向是否符合您的要求,如果不是,您可以将比较的“符号”反转。IE:

if (strcmp(book[i].title,book[j].title)>0)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章