使用通用大小对struct数组进行排序

时间:2014-01-07 07:45:05

标签: c arrays sorting

我是C的新手,我想我的代码远离最佳实践..

我的C程序中有一个struct数组。数组的大小为255(已分配),但并非全部使用。

我的示例中的数组充满了以下vaues:

2;a;121212;121212;0
9;c;121212;121212;1
6;d;121212;121212;1
4;e;121212;121212;1
1;v;121212;121212;1
8;x;121212;121212;1

其余部分用空值填充..(我猜)

现在我的问题不在于实际排序。当我开始排序时,它将会出现一个空的我的数组索引和故障。

一系列书籍:

struct book{
    int ID;
    char name[MAX_STR_LEN];
    char dateIn[DATE_LEN];
    char dateOut[DATE_LEN];
    int isIn;
};


/* array of my books */
struct book books[MAX_BOOKS];

排序功能:

void sort()
{
    /* first find out how many indexes there are */
    int h;
    for (h = 0; h< MAX_BOOKS; h++)
    {
        if (books[h].ID == 0)
        {
            break;
        }
    }

    int j =  0;

    int swaped = 1;
    struct book temp;
    while (swaped == 1)       //bubble sort on the book name
    {
        for(j=0;j< h ;j++)
        {
            swaped = 0;
            if(strcmp(books[j].name,books[j + 1].name)>0)
            {

                //copy to temp val
                temp.ID = books[j].ID;
                strcpy(temp.name,books[j].name);
                strcpy(temp.dateIn,books[j].dateIn);
                strcpy(temp.dateOut,books[j].dateOut);
                temp.isIn = books[j].isIn;


                //copy next val
                books[j].ID = books[j + 1].ID;
                strcpy(books[j].name,books[j + 1].name);
                strcpy(books[j].dateIn,books[j + 1].dateIn);
                strcpy(books[j].dateOut,books[j + 1].dateOut);
                books[j].isIn = books[j + 1].isIn;


                //copy back temp val
                books[j + 1].ID = temp.ID;
                strcpy(books[j+ 1].name,temp.name);
                strcpy(books[j + 1].dateIn,temp.dateIn);
                strcpy(books[j + 1].dateOut,temp.dateOut);
                books[j + 1].isIn = temp.isIn;


                swaped = 1;

            }
        }
    }

}

所以我的问题是,如果可以只对ID不是0的值进行排序吗?

如果您需要更多信息,我会尝试提供..

提前致谢!

3 个答案:

答案 0 :(得分:4)

for(j=0;j< h ;j++)
{
    if(strcmp(books[j].name,books[j + 1].name)>0)
    {

您正在j0转到h-1,包括在内。因此,您要尝试将j == h-1最后一个元素books[j]与下一个books[j+1]进行比较,但不存在。您可能只想查看对h-2 / h-1,即for(j=0; j<h-1; j++)

答案 1 :(得分:3)

为什么你要做这么大的交换计算?你为什么不这么做?

if(strcmp(books[j].name,books[j + 1].name)>0){

   temp = books[j];
   books[j] = books[j+1];
   books[j+1] = temp;
} 

可以对结构数组进行排序。如果你能够交换struct,那么你可以做任何类型的排序算法。

将此条件if(strcmp(books[j].name,books[j + 1].name)>0)更改为if(books[j].ID>books[j + 1].id),然后您可以针对ID对结构进行排序。

但请关注@ Nabla的回答。

答案 2 :(得分:2)

Nabla的回答是对的。另外,您将swapped = 0;设置在错误的位置。你有:

while (swapped == 1)       //bubble sort on the book name
{
    for (j = 0; j < h; j++)
    {
        swapped = 0;

但你想:

while (swapped == 1)       //bubble sort on the book name
{
    swapped = 0;
    for (j = 0; j < h; j++)
    {
相关问题