排序结构数组并将其打印到屏幕时遇到问题。当我在Visual Studio 2012中运行代码时,它根本不打印。我花了好几个小时才弄明白,调试模式非常麻烦。我真的很想知道它为什么不按我说的做。
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
struct RandStruct
{
int year;
char string[31];
int frequency;
};
struct RandStruct randArray[150000];
int main(void)
{
int i, j;
for (i = 0; i < 150000; i++)
{
randArray[i].year = 150000 - i;
strcpy(randArray[i].string, "test");
randArray[i].frequency = i;
}
for (i = 1; i < 150000; i++)
{
for (j = 0; j < 150000 - i; j++)
{
if (randArray[j].year > randArray[j+1].year)
{
struct RandStruct temp = randArray[j];
randArray[j] = randArray[j+1];
randArray[j+1] = temp;
}
}
}
for (i = 0; i < 150000; i++)
{
printf("%d,%s,%d\n", randArray[i].year, randArray[i].string, randArray[i].frequency);
}
return 0;
}
最佳答案
对于排序,应该使用qsort函数,而不是重新创建轮子。
#include <stdlib.h>
int my_compar(const void *a, const void *b) {
const struct RandStruct *aa = a;
const struct RandStruct *bb = b;
if(aa->year < bb->year) return -1;
if(aa->year == bb->year) return 0;
return 1;
}
int main(void) {
... other stuff ...
size_t size = sizeof(struct RandStruct);
qsort(randArray, sizeof(randArray)/size, size, my_compar);
}