Le tri rapide choisit un pivot, répartit les valeurs autour de lui et recommence sur chaque partie. Ici, le pivot est toujours la première valeur. Si les parties sont équilibrées, le temps est Θ(n log n). Si le pivot est toujours un extrême, le temps monte à Θ(n²). Avec ce choix de pivot, cela arrive aussi quand les valeurs sont déjà triées.
Exemple simple
Choisir 2 comme pivot. Déplacer 1 vers la gauche et 3 vers la droite. Chaque côté compte maintenant un élément.
Au départ3 1 2
Résultat1 2 3
lesson.c
#include <stdbool.h>
#include <stdio.h>
int main(void) {
int values[] = {3, 1, 2};
int pivot = values[2];
int boundary = 0;
int i = 0;
while (i < 2) {
if (values[i] < pivot) {
int saved = values[i];
values[i] = values[boundary];
values[boundary] = saved;
boundary += 1;
}
i += 1;
}
values[2] = values[boundary];
values[boundary] = pivot;
i = 0;
while (i < 3) {
printf("%d\n", values[i]);
i += 1;
}
}
Sortie
1
2
3
Exemples du quotidien
Répartir les colis selon un poids de référence
Trois colis pèsent 8, 2 et 5 kilos. Prenez 5 comme poids de référence. Quel colis va de chaque côté ?
Au départ8 2 5
Résultat2 • 5 • 8
Deux est plus léger et huit est plus lourd. Le pivot sépare maintenant les deux groupes.
Traiter des livres au même prix
Chaque livre coûte 4. Qu'est-ce qu'une partition en trois parties produirait ?
Au départ4 4 4
Résultat∅ • 4 4 4 • ∅
Le groupe égal contient tous les livres. Aucun des groupes externes n'a besoin de travail supplémentaire.
Repérer un pivot mal choisi
Les dates 1, 2, 3 et 4 sont dans l'ordre. Toujours choisir la dernière date. Qu'est-ce qui se passe lors du premier split ?
Au départ1 2 3 4
Résultat1 2 3 • 4 • ∅
Un groupe tient encore trois éléments. En répétant ce modèle, on gaspille des comparaisons.
Coût et limites
Des partitions équilibrées mènent généralement à un travail de O(n log n). En choisissant répétéement un pivot extrême, on peut atteindre O(n²).
Complexité en temps
Meilleur cas: Θ(n log n)
Cas moyen: Θ(n log n)
Pire cas: Θ(n²)
Tri rapide en C
Code source en C
#include<stdio.h>
int partition(int arr[], int low, int high) {
int pivot = arr[low];
int i = low;
int j = high;
while(i < j) {
while(arr[i] <= pivot && i < high) {
i++;
}
while(arr[j] > pivot && j > low) {
j--;
}
if(i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
arr[low] = arr[j];
arr[j] = pivot;
return j;
}
void quickSort(int arr[], int low, int high) {
if(low < high) {
int pivot = partition(arr, low, high);
quickSort(arr, low, pivot - 1);
quickSort(arr, pivot + 1, high);
}
}
void printArray(const int arr[], size_t size) {
for(size_t i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main(int argc, const char * argv[]) {
int arr[] = { 15, 3, 12, 6, -9, 9, 0 };
const size_t SIZE = sizeof(arr) / sizeof(*arr);
printf("Before Sorting: ");
printArray(arr, SIZE);
quickSort(arr, 0, (SIZE - 1));
printf("After Sorting: ");
printArray(arr, SIZE);
return 0;
}
Sortie
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Publicités
Suivez l’exemple étape par étape
Commencez avec [15, 3, 12, 6, -9, 9, 0].
Utilisez la première valeur, 15, comme pivot. Parcourez vers l'intérieur à partir des deux extrémités.
Avance l'indice de gauche tant que sa valeur est inférieure ou égale au pivot et que l'indice est en dessous de la borne supérieure. Déplace l'indice de droite vers la gauche tant que sa valeur dépasse le pivot.
Si les indices n'ont pas rencontré, échangez les deux valeurs mal placées et continuez le balayage.
Lorsque les indices se rencontrent ou se croisent, échanger la première valeur avec celle à l'indice de droite. Le pivot est maintenant en sa position finale.
Triez récursivement les intervalles avant et après cette position. Un intervalle avec moins de deux éléments est déjà trié.
Tri rapide en C, étape par étape
Code source en C
#include<stdio.h>
int partition(int arr[], int low, int high) {
// Pick a lowest bound element as an pivot value
int pivot = arr[low];
int i = low;
int j = high;
while(i < j) {
// Increment the index value of "i"
// till the left most values should be less than or equal to the pivot value
while(arr[i] <= pivot && i < high) {
i++;
}
// Decrement the index value of "j"
// till the right most values should be greater than to the pivot value
while(arr[j] > pivot && j > low) {
j--;
}
// Interchange the values of present
// in the index i and j of an array only if i is less than j
if(i < j) {
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
}
// Interchange the element in j's poisition to the lower bound of an array
// and place the Pivot element to the j's position
arr[low] = arr[j];
arr[j] = pivot;
// Finally return the appropriate index position of the pivot element
return j;
}
void quickSort(int arr[], int low, int high) {
if(low < high) {
// Find the pivot index of the lower bound of an array
int pivot = partition(arr, low, high);
// Apply Divide and conquer strategy
// to sort the left side and right side of an array
// respective to the pivot position
// Left hand side array
quickSort(arr, low, pivot - 1);
// Right hand side array
quickSort(arr, pivot + 1, high);
}
}
void printArray(const int arr[], size_t size) {
// Loop the item and print each item in the console with white space seperated
for(size_t i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main(int argc, const char * argv[]) {
int arr[] = { 15, 3, 12, 6, -9, 9, 0 };
const size_t SIZE = sizeof(arr) / sizeof(*arr);
printf("Before Sorting: ");
printArray(arr, SIZE);
quickSort(arr, 0, (SIZE - 1));
printf("After Sorting: ");
printArray(arr, SIZE);
return 0;
}
Sortie
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15