c - 数组的选择排序结构问题

标签 c arrays sorting struct

因此,我使用选择排序对学生 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)未进行排序。

最佳答案

更正的代码:

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;
}

关于c - 数组的选择排序结构问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34735997/

相关文章:

algorithm - 查找链表中的乱序元素

c++ - 删除重复项和对 vector 进行排序的最有效方法是什么?

c - 循环文本以匹配 C 中两个链接列表之间的字符计数

javascript - 嵌套循环中的总和返回不正确

c - 是否可以将变量从一个进程传递到另一个进程?

arrays - 更新 Matlab 结构数组的每个元素中的一个字段

javascript - 将一维数组插入二维数组的谷歌脚本

mongodb - 我如何在 MongoDB 中按 $elemMatch 排序?

c++ - 如何在Arduino-ESP8266上从C/C++中的字符串解析time_t?

c - 命名管道和后台进程