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 DS18B20内部ADC模数转换器
  • ¥15 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动