【问题标题】:How to implement Insertion Sort with an array of structures in C?如何用C中的结构数组实现插入排序?
【发布时间】:2016-06-02 15:44:07
【问题描述】:

我正在尝试对结构数组进行排序,但我不知道我做错了什么......

这是我的结构:

typedef struct{
    char name[15];
    char score[15];
}scores;

这是我的文件:

Eric 2500
John 4000
Chris 2000
Karen 1000
Lizzie 3000

我读了文件,所以现在我的结构有名称和分值,但是当我尝试使用我同学给我的插入排序算法对其进行排序时:

void InsertionSort(scores records[RP])
{
    int pos, i;
    scores structInsert;

    for(i=1; i<=RP; i++)
    {
        strcpy(structInsert.name, records[i].name);
        strcpy(structInsert.score, records[i].score);

        pos=i;

        while(pos>0 && records[pos-1].score > structInsertar.score)
        {
            strcpy(structInsert.name, records[i].name);
            strcpy(structInsert.score, records[i].score);
            pos--;
        }

        if(pos!=i)
        {
            strcpy(records[pos].name, structInsert.name);
            strcpy(records[pos].score, structInsert.score);
        }
    }
}

“排序”后的输出是这样的:

?2-s //Trash, Eric is gone
John 4000
Chris 2000
Karen 1000
Lizzie 3000

没有排序,请帮忙!顺便说一句,分数是一个字符,因为它是用于游戏的outtextxy()

【问题讨论】:

  • 范围i&lt;=RP 似乎是错误的,因为我猜records 根据代码scores records[RP] 只有RP 元素(尽管这实际上相当于scores *records 以及有关数量的信息元素将消失)。请发帖Minimal, Complete, and Verifiable example
  • 比较records[pos-1].score &gt; structInsertar.score是什么意思?由于score 字段是一个字符数组,所以上面的比较比较的是数组的地址,而不是存储的实际值(这是我假设的意图)。此外,第二个循环中的复制没有意义,因为i 在循环中没有更改。
  • 您在如何(不)移动数组中的元素方面也存在问题。您仅在数组和临时空间之间执行复制,但在内部循环中,您需要将元素从数组中的一个位置复制到另一个位置。

标签: c arrays sorting struct


【解决方案1】:

您似乎正在通过读取超出范围的数组导致未定义的行为

尝试将i&lt;=RP 更改为i&lt;RP 以避免off-by-one error

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-25
    • 2013-12-15
    • 2013-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多