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.

GoData Integrity

Code

gosnippet
22 lines
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

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.