Last active
November 14, 2016 13:05
-
-
Save RichardKnop/fc2266f544cca3b9011b213950a375f7 to your computer and use it in GitHub Desktop.
Two alternative quicksort implementations
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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