github.com/ks888/tgo@v0.0.0-20190130135156-80bf89407292/_examples/qsort.go (about) 1 package main 2 3 import ( 4 "fmt" 5 6 "github.com/ks888/tgo/lib/tracer" 7 ) 8 9 func qsort(data []int, start, end int) { 10 if end-start <= 1 { 11 return 12 } 13 14 index := partition(data, start, end) 15 qsort(data, start, index-1) 16 qsort(data, index, end) 17 return 18 } 19 20 func partition(data []int, start, end int) int { 21 pivot := data[(start+end)/2] 22 left, right := start, end 23 for { 24 for left <= end && data[left] < pivot { 25 left++ 26 } 27 for right >= start && data[right] > pivot { 28 right-- 29 } 30 if left > right { 31 return left 32 } 33 34 data[left], data[right] = data[right], data[left] 35 left++ 36 right-- 37 } 38 } 39 40 func main() { 41 tracer.SetTraceLevel(2) // will be explained later 42 tracer.Start() 43 44 testdata := []int{3, 1, 2, 5, 4} 45 qsort(testdata, 0, len(testdata)-1) 46 47 tracer.Stop() 48 49 fmt.Println(testdata) 50 }