1.nums[0]作为core,将nums中大于core的元素放入greater,将不大于core的元素放入less 当nums长度为1时往ch中写入此元素 2.分别对less和greater进行1操作(并行) 3.读取2操作中写入的ch,先读less再读core最后读greater保证大小顺序 const Length = 10000 func quickSort(nums []int, ch chan int) { if len(nums) == 0 { close(ch) return } if len(nums) == 1 { ch <- nums[0] close(ch) return } less, greater := []int{}, []int{} core := nums[0] nums = nums[1:] for _, v := range nums { if v <= core { less = append(less, v) } else { greater = append(greater, v) } } leftCh, rightCh := make(chan int, len(less)), make(chan int, len(greater)) go quickSort(less, leftCh) go quickSort(greater, rightCh) for v := range leftCh { ch <- v } ch <- core for v := range rightCh { ch <- v } close(ch) return } func main() { nums := []int{} ch := make(chan int, Length) //缓冲channel //var ch chan int fmt.Println(ch == nil) for i := 0; i < Length; i++ { nums = append(nums, rand.Int()) //初始化数组,长度Length = 10000 } now := time.Now() quickSort(nums, ch) fmt.Println("数组长度:", Length, " 耗时:", time.Since(now)) }
false
default
数组长度: 10000 耗时: 14.68245ms