je le Quicksort suivant qui choisit toujours le premier élément de la sous-séquence comme pivot:La modification de cette Quicksort à toujours utiliser le dernier élément comme le pivot
void qqsort(int array[], int start, int end) {
int i = start; // index of left-to-right scan
int k = end; // index of right-to-left scan
if (end - start >= 1) { // check that there are at least two elements to sort
int pivot = array[start]; // set the pivot as the first element in the partition
while (k > i) { // while the scan indices from left and right have not met,
while (array[i] <= pivot && i <= end && k > i) // from the left, look for the first element greater than the pivot
i++;
while (array[k] > pivot && k >= start && k >= i) // from the right, look for the first element not greater than the pivot
k--;
if (k > i) // if the left seekindex is still smaller than the right index, swap the corresponding elements
swap(array, i, k);
}
swap(array, start, k); // after the indices have crossed, swap the last element in the left partition with the pivot
qqsort(array, start, k - 1); // quicksort the left partition
qqsort(array, k + 1, end); // quicksort the right partition
} else { // if there is only one element in the partition, do not do any sorting
return;
}
}
Maintenant, comme vous pouvez le voir, cet algorithme toujours prend le premier élément à être le pivot: int pivot = array[start];
Je veux modifier cet algorithme pour qu'il utilise toujours le dernier élément au lieu du premier élément de la sous-séquence, car je veux analyser les temps de fonctionnement physiques des deux implémentations.
J'ai essayé de changer la ligne int pivot = array[start];
-int pivot = array[end];
mais l'algorithme puis en sortie une séquence non triés:
//Changes: int pivot = array[end];
unsorted: {5 4 3 2 1}
*sorted*: {1 2 5 4 3}
Pour tester un autre pivot, j'ai aussi essayé d'utiliser l'élément central de la sous-séquence, mais l'algorithme toujours pas:
//Changes: int pivot = array[(start + end)/2];
unsorted: {5 3 4 2 1}
*sorted*: {3 2 4 1 5}
quelqu'un peut-il s'il vous plaît me aider à comprendre cet algorithme correctement et me dire quels changements dois-je faire pour Suc ont cessfully cette mise en œuvre toujours choisir le dernier élément de la sous-séquence comme le pivot?
Quelque chose est arrivé étrange à vos accolades. Il semble que certains ont été commentés, d'autres ont été supprimés et l'un d'entre eux est resté. Essayez de republier votre code. – colithium
@colithium - merci pour cela ... ne l'a pas remarqué; réparé maintenant. –