dongquechan4414 2015-11-18 13:11
浏览 49
已采纳

排序多维数组/切片

I have created a multidimensional array (slice) in Go as follows:

var distancematrix [5][5]int

So it is a 5*5 array/slice. Now I am inserting values into this slice such that at a point:

distancematrix :  [[0 154 12 35 138] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]]

Now, I want to sort this array in ascending order, e.g.:

sorteddistancematrix :  [[0 12 35  138 154] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0] [0 0 0 0 0]]

I tried sort.Ints(distancematrix[0]) but it throws an error saying:

cannot use distancematrix[0] (type [5]int) as type []int in argument to sort.Ints

Basically, I want to fetch the smallest non-zero value in the array. How can I sort this array to achieve this?

  • 写回答

3条回答 默认 最新

  • duanping1632 2015-11-18 13:30
    关注

    To get the smallest non-zero element, you don't need to sort it. Sorting an array or slice is relatively a costly operation - compared to just getting the smallest non-zero element.

    Generally to get the smallest non-zero element, just loop over the values, and look for the value that fits you best. If you find a better one (in your example a smaller non-zero), keep that and continue.

    Example implementation:

    func smallestNonZero(s []int) (n int) {
        for _, v := range s {
            if v != 0 && (v < n || n == 0) {
                n = v
            }
        }
        return
    }
    

    Note: This function will return 0 if and only if the passed slice does not contain any non-zero element (that is, it's either full of 0s or it's empty or it's nil). This function also works properly if the slice (also) contains negative numbers.

    If you have an array and not a slice, simply slice the array (which results in a slice) and so you can pass it to the function above.

    Using it:

    fmt.Println(smallestNonZero([]int{5, 3, 1, 4}))
    fmt.Println(smallestNonZero([]int{0, 3, 5, 8, 0, 2, 9}))
    arr := [5]int{0, 154, 12, 35, 138}
    fmt.Println(smallestNonZero(arr[:]))
    

    Output (try it on the Go Playground):

    1
    2
    12
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大