Sorting
Quick Sort (Lomuto)
Choose the last item as a pivot, partition smaller values to its left, then recurse on the two sides.
Algorithm
Basic Implementation
basic.scala
object Main {
def partition(arr: Array[Int], low: Int, high: Int): Int = {
val pivot = arr(high)
var i = low - 1
for (j <- low until high) {
if (arr(j) <= pivot) {
i = i + 1
val tmp = arr(i); arr(i) = arr(j); arr(j) = tmp
}
}
val tmp = arr(i + 1); arr(i + 1) = arr(high); arr(high) = tmp
i + 1
}
def quickSort(arr: Array[Int], low: Int, high: Int): Unit = {
if (low < high) {
val pivotIndex = partition(arr, low, high)
quickSort(arr, low, pivotIndex - 1)
quickSort(arr, pivotIndex + 1, high)
}
}
def main(args: Array[String]): Unit = {
val arr = Array(4, 1, 5, 2, 3)
quickSort(arr, 0, arr.length - 1)
println(arr.mkString("[", ", ", "]"))
}
}
Complexity
- Time: O(n^2) worst, O(n log n) average
- Space: O(log n) average call stack
- Stable: no
Implementation notes
val arr = Array(4, 1, 5, 2, 3)fixes the ScalaArray[Int]reference, butpartitionandquickSortmutate its slots in place.partition(arr: Array[Int], low: Int, high: Int): Intchooses the last slot withval pivot = arr(high).var i = low - 1marks the end of the left side. The scanfor (j <- low until high)uses Scala's exclusiveuntil, sojvisits0,1,2, and3while the pivot stays at index4.- When
arr(j) <= pivot, the code incrementsiand performs an explicit temporary-variable swap:val tmp = arr(i); arr(i) = arr(j); arr(j) = tmp. - The first partition compares against pivot
3:4stays right,1swaps left to make[1, 4, 5, 2, 3],5stays right, and2swaps left to make[1, 2, 5, 4, 3]. - After the scan, a second explicit
tmpswap moves the pivot intoi + 1, producing[1, 2, 3, 4, 5]with pivot index2. quickSortrecurses only whenlow < high; the replay then summarizes the already-sorted left side[1, 2]and right side[4, 5].println(arr.mkString("[", ", ", "]"))prints the final array exactly as[1, 2, 3, 4, 5].
pivot
The final element is moved to the boundary between smaller and larger values.
partition
One scan rearranges the current range before the recursive calls.