Skip to content

Instantly share code, notes, and snippets.

@RichardKnop
Last active November 14, 2016 13:05
Show Gist options
  • Save RichardKnop/fc2266f544cca3b9011b213950a375f7 to your computer and use it in GitHub Desktop.
Save RichardKnop/fc2266f544cca3b9011b213950a375f7 to your computer and use it in GitHub Desktop.
Two alternative quicksort implementations
package main
import (
"log"
"math/rand"
)
// Quicksort sorts slice of integers from smallest to greatest number
func Quicksort(a []int) []int {
if len(a) < 2 {
return a
}
left, right := 0, len(a)-1
pivot := rand.Int() % len(a)
a[pivot], a[right] = a[right], a[pivot]
for i := range a {
if a[i] < a[right] {
a[left], a[i] = a[i], a[left]
left++
}
}
a[left], a[right] = a[right], a[left]
Quicksort(a[:left])
Quicksort(a[left+1:])
return a
}
func main() {
a := []int{8, 2, 4, 1, 9, 0, 23, 60, 120, 4, 200, 7}
log.Print(Quicksort(a))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment