因此,我使用选择排序对学生 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/