Skip to content

Instantly share code, notes, and snippets.

@maxclav
Last active September 18, 2022 18:14
Show Gist options
  • Save maxclav/e8b19dcfe63a31f60c71f8a268b4dde1 to your computer and use it in GitHub Desktop.
Save maxclav/e8b19dcfe63a31f60c71f8a268b4dde1 to your computer and use it in GitHub Desktop.
Simple and custom quicksort in Go (GoLang).
package slice
// For learning purpose only.
// Please, use the sort package of Go's Standard library: https://pkg.go.dev/sort
// Quicksort sorts the slice `vals` with the
// quicksort algorithm.
// Time: O(nlogn)
// Space: O(logn)
func Quicksort(vals []int) {
if len(vals) < 2 {
return
}
// Pick a pivot (random)
// and swap it with the value at the last index
pivot := rand.Int() % len(vals)
vals[pivot], vals[len(vals)-1] = vals[len(vals)-1], vals[pivot]
pivot = len(vals) - 1
// Pile elements smaller than the pivot on the left
lastSmaller := 0
for idx, val := range vals {
if val < vals[pivot] {
vals[idx], vals[lastSmaller] = vals[lastSmaller], vals[idx]
lastSmaller++
}
}
// Place the pivot after the last smaller element
vals[lastSmaller], vals[pivot] = vals[pivot], vals[lastSmaller]
// Go down the rabbit hole
Quicksort(vals[:lastSmaller])
Quicksort(vals[lastSmaller+1:])
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment