package algorithm
import (
"math/rand"
"testing"
"time"
)
func quickSort(data []int) {
sortWithinScope(data, 0, len(data)-1)
}
func sortWithinScope(data []int, start int, end int) {
if start < end {
pivot := partition(data, start, end)
sortWithinScope(data, start, pivot-1)
sortWithinScope(data, pivot+1, end)
}
}
func partition(data []int, start int, end int) int {
ref := data[end]
nextLowerIndex := start
for i := start; i < end; i++ {
if data[i] < ref {
data[nextLowerIndex], data[i] = data[i], data[nextLowerIndex]
nextLowerIndex++
}
}
data[nextLowerIndex], data[end] = data[end], data[nextLowerIndex]
return nextLowerIndex
}
func equal(a, b []int) bool {
if len(a) != len(b) {
return false
}
for i, v := range a {
if v != b[i] {
return false
}
}
return true
}
func TestEmpty(t *testing.T) {
count := 10
toSort := make([]int, 0)
expect := make([]int, 0)
for i := 0; i < count; i++ {
toSort = append(toSort, i)
expect = append(expect, i)
}
rand.Seed(time.Now().UnixNano())
rand.Shuffle(len(toSort), func(i, j int) { toSort[i], toSort[j] = toSort[j], toSort[i] })
quickSort(toSort)
if !equal(expect, toSort) {
t.Error("soft failed")
}
}
评论 (1 条评论)