Skip to content

Instantly share code, notes, and snippets.

@kaneshin
Created August 29, 2015 12:19
Show Gist options
  • Save kaneshin/8c2c86d88194147cf861 to your computer and use it in GitHub Desktop.
Save kaneshin/8c2c86d88194147cf861 to your computer and use it in GitHub Desktop.
func qsort(a []int) []int {
if len(a) < 2 { return a }
left, right := 0, len(a) - 1
// Pick a pivot
pivotIndex := rand.Int() % len(a)
// Move the pivot to the right
a[pivotIndex], a[right] = a[right], a[pivotIndex]
// Pile elements smaller than the pivot on the left
for i := range a {
if a[i] < a[right] {
a[i], a[left] = a[left], a[i]
left++
}
}
// Place the pivot after the last smaller element
a[left], a[right] = a[right], a[left]
// Go down the rabbit hole
qsort(a[:left])
qsort(a[left + 1:])
return a
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment