免责声明:我的程序中的某些单词是法语。
我需要读取一个包含 118 名学生的学生编号、姓名、名字和年级的文件。然后使用quicksort()
将这些学生从最高年级重新排列到最低年级。当我运行我的程序时,每个年级突然变得0,00
。我知道我的快速排序本身没有任何问题,问题在于变量note
(等级(的问题。有人可以帮忙吗?
#include <stdio.h>
#include <ctype.h>
#include <string.h>
#define MAX_PERS 200
#define MAX_LONG_NP 15
typedef struct
{
int numero;
char nom[MAX_LONG_NP];
char prenom[MAX_LONG_NP];
float note;
} donnees;
donnees tab[MAX_PERS];
int nbPers=0;
void lire(donnees tab[], int *n)
{
FILE *aLire = fopen("notes.txt", "r");
int nb=0;
while(!feof(aLire))
{
fscanf(aLire, "%d%s%s%fn", &tab[nb].numero, &tab[nb].nom, &tab[nb].prenom, &tab[nb].note);
nb++;
}
fclose(aLire);
*n = nb;
}
void afficher(donnees tab[], int nb, char *quand)
{
int i;
printf("Contenu du tableau %s le trinn", quand);
for(i=0; i<nb; i++)
printf( "%4d %15s %15s %3.2fn", tab[i].numero, tab[i].nom, tab[i].prenom, tab[i].note);
printf("nn");
}
void echanger (donnees *P1, donnees *P2)
{
donnees tempo;
tempo = *P1 ;
*P1 = *P2;
*P2 = tempo;
}
void partitionner ( donnees tab[], int debut, int fin, int *P )
{
int G = debut , D = fin ;
float Val_Pivot = tab[debut].note;
while ( G <= D && tab[G].note >= Val_Pivot) G++;
while ( tab[D].note < Val_Pivot) D--;
if ( G < D ) echanger(&tab[G], &tab[D]);
while ( G <= D ) ;
echanger (&tab[debut], &tab[D]);
*P = D ;
}
void quickSort ( donnees tab[], int gauche, int droite )
{
int indPivot ;
if (gauche < droite)
{
partitionner ( tab, gauche, droite, &indPivot);
quickSort ( tab, gauche, indPivot - 1 );
quickSort ( tab, indPivot + 1, droite);
}
}
int main()
{
donnees tab[MAX_PERS];
lire(tab, &nbPers);
afficher(tab, nbPers, "avant");
quickSort(tab, 0, nbPers-1);
afficher(tab, nbPers, "apres");
return 0;
}
编辑
以下是文件中的前五个条目:
1000 Docteur Albert 65.5
1001 Solo Hanz 23.4
1002 Caillou Frederic 78.7
1003 Viky Bryan 98.6
1004 Encas Christian 67.7
这些是输出中的前五个条目:
1000 Docteur Albert 0.00
1001 Solo Hanz 0.00
1002 Caillou Frederic 0.00
1003 Viky Bryan 0.00
1004 Encas Christian 0.00
您对某些数据集的快速排序没有任何问题,正如我得到以下输出的事实所证明的那样:
Contenu du tableau avant le tri
1 pax diablo 72.00
2 george washington 61.00
3 bilbo baggins 68.00
Contenu du tableau apres le tri
1 pax diablo 72.00
3 bilbo baggins 68.00
2 george washington 61.00
从输入:
1 pax diablo 72
2 george washington 61
3 bilbo baggins 68
因此,您可能遇到一些与代码无关的其他问题。我建议,至少:
- 发布输入文件的小型版本及其生成的输出,假设当您减少输入文件时问题不会消失;
- 确保输入文件的格式完全正确(每个条目四个项目,并且类型正确(,包括没有像"Pax Guido Fortescue Diablo"这样的长名称。
但是,我确实注意到的一件事是在您的分区函数中:
while ( G <= D ) ;
echanger (&tab[debut], &tab[D]);
在某些情况下,第一行末尾的分号将导致无限循环。我不认为这是您的具体问题,因为这会导致没有排序数据的输出,但是一旦第一个问题得到解决,您需要检查一下。
即使您确实删除了该分号,您也会发现它无济于事,因为您永远不会更改该循环中的D
G
。因此,您需要检查交换项目时这些变量会发生什么情况。