Bonjours a tous !
J'ai besoin de développer une fonction de tri par tas générique, voici le .h, le .c et un petit main test :
TasSort.h :
TasSort.c :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 #ifndef _TASSORT_H_ #define _TASSORT_H_ // appel de la fonction de tri par tas, tri suivant Compare, necessite un Swap specifique du type contenu. void TSort (void* array, int lenght, int Compare(void*, int, int), void Swap(void*, int, int)); //construit le tas void construst_tas (void* array, int lenght, int Compare(void*, int, int), void Swap(void*, int, int)); //entasse le tas void entasse (int noeud, void* array, int leght, int Compare(void*, int, int), void Swap(void*, int, int)); #endif
et le main test.c :
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40 #include "TasSort.h" void TSort (void* array, int lenght, int Compare(void*, int, int), void Swap(void*, int, int)) { construct_tas (array, lenght, Compare, Swap); for (int i=lenght-1; i>0; i--) { Swap (array, 0, i); entasse (0, array, lenght, Compare, Swap); } } void construct_tas (void* array, int lenght, int Compare(void*, int, int), void Swap(void*, int, int)) { for(int i= (lenght/2) - 1; i >= 0; i--) entasse (i, array, lenght, Compare, Swap); } void entasse (int noeud, void* array, int lenght, int Compare(void*, int, int), void Swap(void*, int, int)) { int max = noeud, gauche = 2*noeud + 1, droite = gauche + 1; if (gauche < lenght && (Compare(array, gauche, max))) max = gauche; if (droite < lenght && (Compare(array, droite, max))) max = droite; if (max != noeud) { Swap (array, noeud, max); entasse (max, array, lenght, Compare, Swap); } } // visiblement, il y a des swaps qui ne sont tout bonnement pas pris en compte...
mon problème ce situe au niveau de la fonction Swap (ligne 6 du main) : appliqué ici, il semble parfois bien fonctionner parfois... n'avoir aucun effet,
Code : Sélectionner tout - Visualiser dans une fenêtre à part
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30 #include "TasSort.h" #include <stdio.h> #include <stdlib.h> void intSwap (void* array, int i, int j) { int temp = ((int*)array)[i]; ((int*)array)[i] = ((int*)array)[j]; ((int*)array)[j] = temp; } void smallest (void* array, int i, int j) { return (((int*)array)[i] <= ((int*)array)[j]); } int main (void) { int testouille[10] = {2, 4, 2, 6, 8, 3, 3, 12, 1, 0}; TSort(testouille, 10, smallest, intSwap); printf("\n"); for (int i=0; i<10; i++) printf ("%d ", testouille[i]); printf("\n"); return 0; }
du coup a la fin le tableau est trié n'importe comment... j'ai cherché partout la solution, sans succès, est-ce que vous pouvez m'aider à résoudre ce problème ?
Merci pour toute réponse !
Partager