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.kt
fun main() {
var values = intArrayOf(3, 1, 2)
var pivot = values[2]
var boundary = 0
var i = 0
while (i < 2) {
if (values[i] < pivot) {
var 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) {
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 Kotlin
Quellcode in Kotlin
fun quickSort(arr: IntArray, low: Int, high: Int) {
if(low < high) {
val pivot: Int = partition(arr, low, high)
quickSort(arr, low, pivot - 1)
quickSort(arr, pivot + 1, high)
}
}
fun partition(arr: IntArray, low: Int, high: Int): Int {
val pivot = arr[low]
var i: Int = low
var j: Int = high
while(i < j) {
while(arr[i] <= pivot && i < high) {
i++
}
while(arr[j] > pivot && j > low) {
j--
}
if(i < j) {
val temp: Int = arr[i]
arr[i] = arr[j]
arr[j] = temp
}
}
arr[low] = arr[j]
arr[j] = pivot
return j
}
fun printArray(arr: IntArray) {
val lastIndex: Int = arr.size - 1
for (i in 0..lastIndex) {
val num = arr[i]
print("$num ")
}
println("")
}
fun main(args: Array<String>) {
val arr: IntArray = intArrayOf(15, 3, 12, 6, -9, 9, 0)
print("Before Sorting: ")
printArray(arr)
quickSort(arr, 0, arr.size - 1)
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 Kotlin mit Erklärung
Quellcode in Kotlin
fun quickSort(arr: IntArray, low: Int, high: Int) {
if(low < high) {
// Find the pivot index of the lower bound of an array
val pivot: Int = 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)
}
}
fun partition(arr: IntArray, low: Int, high: Int): Int {
// Pick a lowest bound element as an pivot value
val pivot = arr[low]
var i: Int = low
var j: Int = high
while(i < j) {
// Increment the index value (i.e. i )
// till the left most values should be less than or equal to the pivot value
while(arr[i] <= pivot && i < high) {
i++
}
// Increment the index value (i.e. 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) {
val temp: Int = 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
return j
}
fun printArray(arr: IntArray) {
val lastIndex: Int = arr.size - 1
// Loop the item and print each item in the console with white space seperated
for (i in 0..lastIndex) {
val num = arr[i]
print("$num ")
}
println("")
}
fun main(args: Array<String>) {
val arr: IntArray = intArrayOf(15, 3, 12, 6, -9, 9, 0)
print("Before Sorting: ")
printArray(arr)
quickSort(arr, 0, arr.size - 1)
print("After Sorting: ")
printArray(arr)
}
Ausgabe
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15