Skip to content

Instantly share code, notes, and snippets.

@paulodiniz
Created February 7, 2017 11:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paulodiniz/ee70265ae4e62ca4163db3f22f2951dc to your computer and use it in GitHub Desktop.
Save paulodiniz/ee70265ae4e62ca4163db3f22f2951dc 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