du0923 2019-06-25 08:42
浏览 37
已采纳

如何修复并发合并排序

I am trying to learn go lang and facing problems in implementing merge sort concurrently. It is not sorting the array properly

I have tried finding any race conditions and also tried printing at various stages. But couldn't seem to figure out the issue. Any tool to analyze and point out such issues.

package main

import (
    "fmt"
    "time"
)

func merge(a []int, ch chan int) {
    //     defer close(ch)
    if len(a) == 0 {
        close(ch)
        return
    }

    if len(a) == 1 {
        ch <- a[0]
        close(ch)
        return
    }

    mid := len(a) / 2

    ch1 := make(chan int)
    go merge(a[:mid], ch1)

    ch2 := make(chan int)
    go merge(a[mid:], ch2)

    v1, ok1 := <-ch1
    v2, ok2 := <-ch2
    var t []int
    for ok1 == true && ok2 == true {
        if v1 < v2 {
            ch <- v1
            t = append(t, v1)
            v1, ok1 = <-ch1
        } else {
            ch <- v2
            t = append(t, v2)
            v2, ok2 = <-ch2
        }
    }
    close(ch)
}

func Merge(a []int) (sortedA []int) {
    ch := make(chan int)
    go merge(a, ch)

    for v := range ch {
        sortedA = append(sortedA, v)
    }
    return
}

func main() {
    arr := []int{3, 34, 23, 65, 34, 7, -1, 0, -23}
    start := time.Now()
    b := Merge(arr)
    fmt.Printf("Time taken to sort: %v, sorted: %v", time.Since(start), b)
}

I expected the output to be [-23 -1 0 3 7 23 34 34 65] but the actual output is only -23

  • 写回答

1条回答 默认 最新

  • duan198727 2019-06-25 09:12
    关注

    Your merge phase is broken: You have to send on ch all values from ch1 and ch2 but your code stops once any of ch1 or ch2 is drained. Once you drained e.g. ch2 you have to send everything from ch1 to c.

    Something along (make sure to clean up the conditions!)

    for ok1 || ok2 {
        if (ok1 && ok2 && v1 < v2) || (ok1 && !ok2) {
            ch <- v1
            v1, ok1 = <-ch1
        } else if (ok1 && ok2 && v1 >= v2) || (!ok1 && ok2) {
            ch <- v2
            v2, ok2 = <-ch2
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 各位请问平行检验趋势图这样要怎么调整?说标准差差异太大了
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 wpf界面一直接收PLC给过来的信号,导致UI界面操作起来会卡顿
  • ¥15 init i2c:2 freq:100000[MAIXPY]: find ov2640[MAIXPY]: find ov sensor是main文件哪里有问题吗
  • ¥15 运动想象脑电信号数据集.vhdr
  • ¥15 三因素重复测量数据R语句编写,不存在交互作用
  • ¥15 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab