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.go
package main
import "fmt"
func partition(arr []int, low int, high int) int {
pivot := arr[high]
i := low - 1
for j := low; j < high; j++ {
if arr[j] <= pivot {
i++
arr[i], arr[j] = arr[j], arr[i]
}
}
arr[i+1], arr[high] = arr[high], arr[i+1]
return i + 1
}
func quickSort(arr []int, low int, high int) {
if low < high {
pivotIndex := partition(arr, low, high)
quickSort(arr, low, pivotIndex-1)
quickSort(arr, pivotIndex+1, high)
}
}
func main() {
arr := []int{4, 1, 5, 2, 3}
quickSort(arr, 0, len(arr)-1)
fmt.Println(arr)
}
Complexity
- Time: O(n^2) worst, O(n log n) average
- Space: O(log n) average call stack
- Stable: no
Implementation notes
- Go builds
arrwith the slice literal[]int{4, 1, 5, 2, 3};quickSortreceives that slice header and mutates the shared backing array in place. quickSort(arr, low, high)recurses only whenlow < high;mainstarts with bounds0andlen(arr)-1.- Lomuto partition chooses
pivot := arr[high], initializesi := low - 1, and scansj := low; j < high; j++. - Comparisons use
arr[j] <= pivot; when true,i++runs before the tuple swaparr[i], arr[j] = arr[j], arr[i]. The pivot is placed witharr[i+1], arr[high] = arr[high], arr[i+1]. - The trace records the first partition: keep
4, swap1left, keep5, swap2left, then swap pivot3into index2, producing[1, 2, 3, 4, 5]. - Recursive calls on left
[1, 2]and right[4, 5]are summarized in the trace; there is no separate bad-pivot or degradation trace frame here. fmt.Println(arr)prints Go's default slice format[1 2 3 4 5]. Indexed accesses rely on the checkedlow/highbounds and Go's normal bounds checks.
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.