【问题标题】:Selection Sort of array Struct issues数组结构问题的选择排序
【发布时间】:2016-01-12 05:08:40
【问题描述】:

所以我让我的选择排序根据学生 ID 号对结构的学生数组列表进行排序。我遇到的问题是它不只对每个文件的最后两个进行排序,而且我不知道出了什么问题。

void assortList(STUDENT* list, int size)
{
    int startScan;
    int minIndex;
    int minValue;

    for(startScan = 0; startScan < (size - 1); startScan++)
    {
        minIndex = startScan;
        minValue = list[startScan].ID;
        for(int index = startScan + 1; index < size; index++)
        {
            if(list[index].ID < minValue)
            {
                minValue = list[index].ID;
                minIndex = index;
            }
            STUDENT temp = list[minIndex];
            list[minIndex] = list[startScan];
            list[startScan] = temp;
        }
    }

    for(int x = 0; x < size; x++)
    {
        FLUSH;
        printf("%d %s\n", list[x].ID, list[x].name);
    }   

    printf("\n");
}

输出

清单 1:

1189 Shmoys, David
1234 Marley, Tom
2901 Green, Mary
2908 Vigoda, Eric
3456 Karlin, Anna
4344 Kelley, Sandra
5445 Homer, Steve
5567 Welch, Jennifer
6566 Williams, Ryan
6579 Vadhan, Salil
8372 Chen, Li
8879 Bein, Wolfgang
8999 Fenner, Mia
9002 Khuller, Samira
9123 Vianu, Victor
9865 Beame, Paul
6766 Hemaspaandra, Lane
8433 Chakrabarti, Amit

清单 2

1111 Tan, Li-Yang
2000 Barenboim, Leonid
2001 Rossman, Marie
3456 Karlin, Anna
4344 Kelley, Sandra
5445 Homer, Steve
5511 Welch, Claire
6577 Green, Susan
8433 Chakrabarti, Amit
8800 Servedio, Rocco
8999 Fenner, Mia
9123 Vianu, Victor
9865 Beame, Paul
6009 Mumey, Brendan
6666 Forbes, Michael

您会从输出中注意到,只是每个列表的最后两个学生(第一组中的 6766、8433;第二组中的 6009 和 6666)没有被排序。

【问题讨论】:

  • 你显示了一些输出;那挺好的。您不显示输入(因此我们不知道哪些已排序或未排序),也没有显示调用该函数的代码。因此,目前还不清楚问题出在哪里。它可能不在您显示的代码中。例如,如果您的计数关闭,您可能会告诉 sort 排序太少的行。如果您的计数器包含数组中分配的最后一个索引,并且在调用排序之前还减去一个,则可能会发生这种情况。不是特别有可能,但有可能——而且我们不可能提供帮助,因为你没有展示出来。
  • @JonathanLeffler 将最后一部分从一个括号移到第一个 for 循环就可以了。对此感到抱歉,下次我一定会发布足够的代码。谢谢。

标签: c arrays sorting struct


【解决方案1】:

更正的代码:

for (startScan = 0; startScan + 1 < size; ++startScan) {
  minIndex = startScan;
  minValue = list[startScan].ID;
  for (int index = startScan + 1; index < size; ++index) {
    if (list[index].ID < minValue) {
      minValue = list[index].ID;
      minIndex = index;
    }
  }
  STUDENT temp = list[minIndex];
  list[minIndex] = list[startScan];
  list[startScan] = temp;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-09-03
    • 2014-05-25
    • 1970-01-01
    • 2017-12-21
    • 2015-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多