[英]C programming: Sorting a integer file while keeping their original place in file
好的,這里有一個小函數可以對程序中編寫的某些值進行排序
#include <stdio.h> /* printf */
#include <stdlib.h> /* qsort */
#include <conio.h> /* getch */
int values[] = { 40, 10, 100, 90, 20, 25 };
int compare (const void * a, const void * b)
{
return ( *(int*)a - *(int*)b );
}
int main ()
{
int n;
qsort (values, 6, sizeof(int), compare);
for (n=0; n<6; n++)
printf ("%d ",values[n]);
getch();
}
這完美地工作,沒有錯誤。
現在,在我的主項目中,我必須對文件中的值進行排序。 我當時想我可以從文件中復制這些值,然后做與此處完全相同的操作。
但是,這似乎很容易,但是我也需要在文件中添加它們的行,因此這意味着我需要第二個數組,其中包含數字1-SIZE。 鑒於我的文件應最大為512行。 我可以采取哪些步驟來完成這項工作?
例:
User ID: Score:
1 13
2 9
3 13
4 19
5 8
6 11
7 14
8 17
應該變成
User ID: Score:
5 8
2 9
6 11
3 13
1 13
7 14
8 17
4 19
這就是你所需要的
#include <stdio.h> /* printf */
#include <stdlib.h> /* qsort */
struct Element
{
int userId;
int score;
};
struct Element elements[] = {
{1, 13},
{2, 9},
{3, 13},
{4, 19},
{5, 8},
{6, 11},
{7, 14},
{8, 17},
};
int ascendingSortCompareFunction (const void * a, const void * b)
{
return (((struct Element *)a)->score - ((struct Element *)b)->score);
}
int descendingSortCompareFunction (const void * a, const void * b)
{
return ((struct Element *)b)->score) - (((struct Element *)a)->score;
}
int main ()
{
int n;
int count;
count = sizeof(elements) / sizeof(elements[0]);
qsort(elements, count, sizeof(elements[0]), ascendingSortCompareFunction);
printf ("UserID\tScore (Ascending Sort)\n");
for (n = 0 ; n < count ; n++)
printf ("%d\t%d\n", elements[n].userId, elements[n].score);
qsort(elements, count, sizeof(elements[0]), descendingSortCompareFunction);
printf ("UserID\tScore (Descending Sort)\n");
for (n = 0 ; n < count ; n++)
printf ("%d\t%d\n", elements[n].userId, elements[n].score);
getchar();
return 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.