Created
February 7, 2017 11:20
-
-
Save paulodiniz/ee70265ae4e62ca4163db3f22f2951dc to your computer and use it in GitHub Desktop.
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
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