go实现快速排序
go实现快速排序
package main import ( "log" ) var c = 0 func main() { var aa []int = []int{5, 2, 3, 11, 13, 27, 1, 38, 0, 6, 4, 7, 9, 15, 33, 30} log.Println(aa) qs(aa) log.Println(aa) // log.Println("quick sort result: ", quickSort(aa)) } /* func quickSort(s []int) []int { if len(s) < 2 { return s } v := s[0] var left, right []int for _, e := range s[1:] { if e <= v { left = append(left, e) } else { right = append(right, e) } } // 实现了“quickSort(left) + v + quickSort(right)”的操作 return append(append(quickSort(left), v), quickSort(right)...) } */ func qs(a []int) { c++ log.Println("agin", a) flag := a[0] l := 0 r := len(a) - 1 bb := false for l <= r { if bb == true { if a[l] > flag { a[r] = a[l] bb = false r-- } else { l++ } } else { if a[r] < flag { a[l] = a[r] bb = true l++ } else { r-- } } if l == r { a[l] = flag log.Println("swap", a) // 先序遍历 if l >= 2 { log.Println("in1", c, l, a) qs(a[0:l]) } if len(a)-l >= 3 { log.Println("in2", c, l, a) qs(a[l+1 : len(a)]) } } } }
中间注释的是参考别人实现的,可以对比分析一下