Quicksort With Median Of Three Pivot (Go)
Sort a slice in place using Go quicksort with median-of-three pivot selection to avoid worst-case behavior.
Code
package main
func quicksort(arr []int, lo, hi int) {
if lo >= hi {
return
}
mid := (lo + hi) / 2
if arr[mid] < arr[lo] { arr[lo], arr[mid] = arr[mid], arr[lo] }
if arr[hi] < arr[lo] { arr[lo], arr[hi] = arr[hi], arr[lo] }
if arr[mid] < arr[hi] { arr[hi], arr[mid] = arr[mid], arr[hi] }
pivot := arr[hi]
i := lo
for j := lo; j < hi; j++ {
if arr[j] < pivot {
arr[i], arr[j] = arr[j], arr[i]
i++
}
}
arr[i], arr[hi] = arr[hi], arr[i]
quicksort(arr, lo, i-1)
quicksort(arr, i+1, hi)
}Inside the snippet
Quicksort With Median Of Three Pivot (Go) is built around the function quicksort.
Iteration happens inside for j := lo; j < hi; j++ — everything outside it runs once.
Using it
The entry-point signature is func quicksort(arr []int, lo, hi int)
Key statements
if arr[mid] < arr[lo] { arr[lo], arr[mid] = arr[mid], arr[lo] }
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.JSON SorterSort JSON object keys by code point ascending or descending, recursively or top-level only, preserving array order.SemVer SorterParse and sort Semantic Version 2.0.0 strings with prerelease and build metadata, respecting prerelease-below-release precedence.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- Are there any imports to resolve outside the language?
- No. Every import resolves against the language's own modules. The file defines `quicksort` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.