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.kt
fun partition(arr: IntArray, low: Int, high: Int): Int {
val pivot = arr[high]
var i = low - 1
for (j in low until high) {
if (arr[j] <= pivot) {
i++
val tmp = arr[i]
arr[i] = arr[j]
arr[j] = tmp
}
}
val tmp = arr[i + 1]
arr[i + 1] = arr[high]
arr[high] = tmp
return i + 1
}
fun quickSort(arr: IntArray, low: Int, high: Int) {
if (low < high) {
val pivotIndex = partition(arr, low, high)
quickSort(arr, low, pivotIndex - 1)
quickSort(arr, pivotIndex + 1, high)
}
}
fun main() {
val arr = intArrayOf(4, 1, 5, 2, 3)
quickSort(arr, 0, arr.size - 1)
println(arr.joinToString(prefix = "[", postfix = "]"))
}
Complexity
- Time: O(n^2) worst, O(n log n) average
- Space: O(log n) average call stack
- Stable: no
Implementation notes
- Kotlin stores the input as a primitive
IntArray;val arris not rebound, butquickSortmutates its slots in place. quickSort(arr: IntArray, low: Int, high: Int)recurses only whenlow < high, then partitions and calls the left and right index ranges aroundpivotIndex.partition(arr, low, high)choosesval pivot = arr[high]and tracks the left boundary with mutablevar i = low - 1.- The Lomuto scan uses
for (j in low until high).if (arr[j] <= pivot)usesIntcomparison and moves equal values to the left side of the pivot. - Swaps use an explicit temporary variable:
val tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp, and the pivot swap uses the same pattern withi + 1andhigh. - No new list or array is allocated during sorting; the extra state is scalar indexes, pivot values, temp variables, and recursive stack frames.
- The trace shows pivot
3:4stays right,1swaps left to[1, 4, 5, 2, 3],5stays right,2swaps left to[1, 2, 5, 4, 3], then pivot3moves to index2as[1, 2, 3, 4, 5]. println(arr.joinToString(prefix = "[", postfix = "]"))formats the mutated array 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.