Quicksort sceglie un valore di riferimento, il pivot, divide la sequenza attorno a quel valore e ripete il lavoro su ciascuna parte. Qui si prende sempre il primo valore come pivot. Con parti bilanciate il tempo è Θ(n log n). Se il pivot è sempre il valore più piccolo o più grande, il tempo sale a Θ(n²). Con questa scelta succede anche quando l’array è già ordinato.
Esempio semplice
Scegliere 2 come il perno. Spostare 1 a sinistra e 3 a destra. Ogni lato ora ha un elemento.
All’inizio3 1 2
Risultato1 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
}
}
Output
1
2
3
Esempi di vita quotidiana
Dividere i pacchi usando un peso di riferimento
Tre pacchi pesano 8, 2 e 5 chili. Usa 5 come peso di riferimento. Quale pacco metti da ciascun lato?
All’inizio8 2 5
Risultato2 • 5 • 8
Due è più leggero e otto è più pesante. Ora il pivot separa i due gruppi.
Gestire libri con lo stesso prezzo
Ogni libro costa 4. Che cosa produrrebbe una partizione a tre vie?
All’inizio4 4 4
Risultato∅ • 4 4 4 • ∅
Il gruppo uguale contiene tutti i libri. Nessun gruppo esterno richiede ulteriore lavoro.
Riconoscere un perno poco adatto
Le date 1, 2, 3 e 4 sono in ordine. Scegli sempre l'ultimo appuntamento. Cosa succede nella prima divisione?
All’inizio1 2 3 4
Risultato1 2 3 • 4 • ∅
Un gruppo contiene ancora tre elementi. Ripeto questo modello spreca confronti.
Costo e limiti
Partizioni bilanciate solitamente richiedono un lavoro di O(n log n). L'uso ripetuto di un pivot estremo può portare a O(n²).
Complessità temporale
Caso migliore: Θ(n log n)
Caso medio: Θ(n log n)
Caso peggiore: Θ(n²)
Quicksort in Kotlin
Codice sorgente 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)
}
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15
Annunci
Segui l’esempio passo per passo
Inizia con [15, 3, 12, 6, -9, 9, 0].
Usa il primo valore, 15, come pivot. Scansiona verso l'interno dai due estremi.
Avanzare l'indice di sinistra mentre il suo valore è al massimo il perno e l'indice è al di sotto del limite superiore. Spostare l'indice destro a sinistra mentre il suo valore supera il pivot.
Se gli indici non si sono incontrati, scambiare i due valori sbagliati e continuare la scansione.
Quando gli indici si incontrano o incrociano, scambiare il primo valore con il valore all'indice giusto. Il perno è ora nella sua posizione finale.
Ordinare ricorsivamente i range prima e dopo quella posizione. Una gamma con meno di due elementi è già ordinata.
Quicksort in Kotlin, passo per passo
Codice sorgente 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)
}
Output
Before Sorting: 15 3 12 6 -9 9 0
After Sorting: -9 0 3 6 9 12 15