Last active
September 9, 2019 05:46
-
-
Save islishude/d90f591e0b7b93da04da90680348e713 to your computer and use it in GitHub Desktop.
quick sort for golang
This file contains hidden or 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 ( | |
"math/rand" | |
"sort" | |
"time" | |
) | |
func main() { | |
slice := rand.Perm(1000) | |
QuickSort(slice) | |
sorted := sort.SliceIsSorted(slice, func(i, j int) bool { | |
return slice[i] < slice[j] | |
}) | |
if !sorted { | |
panic("not sorted") | |
} | |
} | |
// QuickSort is quick sort | |
// TODO: three way quick sort | |
func QuickSort(src []int) { | |
rand.Seed(time.Now().UnixNano()) | |
quickSort(src, 0, len(src)-1) | |
} | |
func quickSort(src []int, l, r int) { | |
if l >= r { | |
return | |
} | |
pos := partition(src, l, r) | |
quickSort(src, l, pos-1) | |
quickSort(src, pos+1, r) | |
} | |
func partition(src []int, l, r int) int { | |
pos := rand.Intn(r-l+1) + l | |
src[pos], src[l] = src[l], src[pos] | |
pivot := src[l] | |
j := l | |
for i := l + 1; i <= r; i++ { | |
if src[i] < pivot { | |
j++ | |
src[j], src[i] = src[i], src[j] | |
} | |
} | |
src[l], src[j] = src[j], src[l] | |
return j | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment