Quicksort wählt einen Pivotwert, teilt die Liste um ihn herum und sortiert die beiden Teile auf dieselbe Weise. Hier ist der erste Wert immer der Pivotwert. Bei ausgeglichenen Teilen beträgt der Zeitaufwand Θ(n log n). Ist der Pivotwert immer der kleinste oder größte, steigt er auf Θ(n²). Mit dieser Wahl passiert das auch bei bereits sortierten Listen.
Ein einfaches Beispiel
Wähle 2 als Pivot. Verschiebe 1 nach links und 3 nach rechts. Jede Seite hat nun ein Element.
Am Anfang3 1 2
Ergebnis1 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;
}
}
Ausgabe
1
2
3
Beispiele aus dem Alltag
Pakete nach einem Vergleichsgewicht aufteilen
Drei Pakete wiegen 8, 2 und 5 Kilo. Nimm 5 als Vergleichswert. Welches Paket kommt auf welche Seite?
Am Anfang8 2 5
Ergebnis2 • 5 • 8
Zwei ist leichter und acht ist schwerer. Die Pivot trennt nun die beiden Gruppen.
Bücher mit gleichem Preis einsortieren
Jedes Buch kostet 4. Was würde eine dreiweg-Partition erzeugen?
Am Anfang4 4 4
Ergebnis∅ • 4 4 4 • ∅
Die gleiche Gruppe enthält jedes Buch. Keine äußere Gruppe benötigt mehr Arbeit.
Eine ungünstige Pivotwahl erkennen
Die Termine 1, 2, 3 und 4 stehen schon in der richtigen Reihenfolge. Wähle jedes Mal den letzten Termin als Vergleichswert. Was passiert bei der ersten Aufteilung?
Am Anfang1 2 3 4
Ergebnis1 2 3 • 4 • ∅
Eine Gruppe hat immer noch drei Elemente. Das Wiederholen dieses Musters verursacht unnötige Vergleiche.
Aufwand und Grenzen
Gleichgewichtige Partitionen führen normalerweise zu einer Arbeitszeit von O(n log n). Das wiederholte Auswählen eines Extrempivots kann jedoch O(n²) ergeben.
Zeitaufwand
Bester Fall: Θ(n log n)
Durchschnittlicher Fall: Θ(n log n)
Schlechtester Fall: Θ(n²)
Quicksort in C
Quellcode in 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;
}
Ausgabe
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Anzeigen
Das Beispiel Schritt für Schritt
Beginne mit [15, 3, 12, 6, -9, 9, 0].
Nutze den ersten Wert, 15, als Pivot. Scanne von beiden Enden hin zum Inneren.
Gehe mit dem linken Index nach rechts, solange sein Wert höchstens so groß wie das Pivot ist und der Index unter der Obergrenze liegt. Gehe mit dem rechten Index nach links, solange sein Wert größer als das Pivot ist.
Solange die beiden Indizes noch nicht aufeinandergetroffen sind, tausche die beiden falsch platzierten Werte und suche weiter.
Wenn die Indizes sich treffen oder schneiden, tausche den ersten Wert mit dem Wert am rechten Index. Der Pivot ist nun an seiner endgültigen Position.
Die Bereiche vor und nach dieser Position rekursiv sortieren. Ein Bereich mit weniger als zwei Elementen ist bereits sortiert.
Quicksort in C mit Erklärung
Quellcode in 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;
}
Ausgabe
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15