For Go 1.18 and above, using generics:
import (
"golang.org/x/exp/constraints"
)
func QuickSort[T constraints.Ordered](a []T) {
if len(a) > 1 {
quickSort(a, 0, len(a)-1)
}
}
func quickSort[T constraints.Ordered](a []T, lo, hi int) {
if lo < hi {
p := partition(a, lo, hi)
quickSort(a, lo, p-1)
quickSort(a, p+1, hi)
}
}
func partition[T constraints.Ordered](a []T, lo, hi int) int {
l, p := lo, findPivot(a, lo, hi)
for r := lo; r < hi; r++ {
if a[r] < a[p] {
a[l], a[r] = a[r], a[l]
l++
}
}
a[l], a[p] = a[p], a[l]
return l
}
// median of three technique
func findPivot[T constraints.Ordered](a []T, lo, hi int) int {
mi := (lo + hi) / 2
if a[lo] > a[mi] {
a[lo], a[mi] = a[mi], a[lo]
}
if a[lo] > a[hi] {
a[lo], a[hi] = a[hi], a[lo]
}
if a[mi] > a[hi] {
a[mi], a[hi] = a[hi], a[mi]
}
a[mi], a[hi-1] = a[hi-1], a[mi]
return hi - 1
}
Usage:
a := []int{1, 8, 4, 9, 6, 3, 5, 2, 7, 0}
fmt.Println(a, "(original)")
QuickSort(a)
fmt.Println(a, "(sorted)")
b := []string{"tuv", "abc", "jkl", "ghi", "mno", "wxyz", "def", "pqrs"}
fmt.Println(b, "(original)")
QuickSort(b)
fmt.Println(b, "(sorted)")