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
main.go
package main
import "fmt"
func main() {
values := []int{3, 1, 2}
pivot := values[2]
boundary := 0
i := 0
for i < 2 {
if values[i] < pivot {
saved := values[i]
values[i] = values[boundary]
values[boundary] = saved
boundary += 1
}
i += 1
}
values[2] = values[boundary]
values[boundary] = pivot
i = 0
for i < 3 {
fmt.Println(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 Go
Quellcode in Go
package main
import (
"fmt"
"strconv"
)
func quickSort(arr []int, low, high int) {
if low < high {
var pivot = partition(arr, low, high)
quickSort(arr, low, pivot - 1)
quickSort(arr, pivot + 1, high)
}
}
func partition(arr []int, low, high int) int {
var pivot = arr[low]
var i = low
var j = high
for i < j {
for arr[i] <= pivot && i < high {
i++;
}
for arr[j] > pivot && j > low {
j--
}
if i < j {
var temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
arr[low] = arr[j]
arr[j] = pivot
return j
}
func printArray(arr []int) {
for i := 0; i < len(arr); i++ {
fmt.Print(strconv.Itoa(arr[i]) + " ")
}
fmt.Println("")
}
func main() {
var arr = []int { 15, 3, 12, 6, -9, 9, 0 }
fmt.Print("Before Sorting: ")
printArray(arr)
quickSort(arr, 0, len(arr) - 1)
fmt.Print("After Sorting: ")
printArray(arr)
}
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 Go mit Erklärung
Quellcode in Go
package main
import (
"fmt"
"strconv"
)
func quickSort(arr []int, low, high int) {
if low < high {
// Find the pivot index of the lower bound of an array
var 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)
}
}
func partition(arr []int, low, high int) int {
// Pick a lowest bound element as an pivot value
var pivot = arr[low]
var i = low
var j = high
for i < j {
// Increment the index value of "i"
// till the left most values should be less than or equal to the pivot value
for 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
for 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 {
var 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
}
func printArray(arr []int) {
// Loop the item and print each item in the console with white space seperated
for i := 0; i < len(arr); i++ {
fmt.Print(strconv.Itoa(arr[i]) + " ")
}
fmt.Println("")
}
func main() {
var arr = []int { 15, 3, 12, 6, -9, 9, 0 }
fmt.Print("Before Sorting: ")
printArray(arr)
quickSort(arr, 0, len(arr) - 1)
fmt.Print("After Sorting: ")
printArray(arr)
}
Ausgabe
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15