func mergeExchangeSort(a []int, lgWorkers int) { n := len(a) if n < 2 { return } top := 2 for top < n { top <<= 1 } top >>= 1 var ( pre = make( []chan struct{}, 1<<lgWorkers, ) post sync.WaitGroup ) worker := func(id int) { for p := top; p != 0; p >>= 1 { d, r := p, 0 for q := top; q >= p; q >>= 1 { <-pre[id] var ( all = n - d quo = all >> lgWorkers rem = all - quo<<lgWorkers at = quo * id do = quo ) if id <= rem { at += id do++ } else { at += rem } for i := at; i < at+do; i++ { if i&p != r { continue } lo, hi := a[i], a[i+d] if lo > hi { a[i], a[i+d] = hi, lo } } post.Done() d, r = q-p, p } } } for id := range pre { pre[id] = make(chan struct{}, 1) go worker(id) } for p := top; p != 0; p >>= 1 { for q := top; q >= p; q >>= 1 { post.Add(len(pre)) for _, pre := range pre { pre <- struct{}{} } post.Wait() } } }
To receive a hint, submit unfixed code.