简体   繁体   English

关于在Golang中对二维数组进行排序的问题

[英]Question about sorting 2 dimensional array in Golang

I have a question about 2 dimensional array in GoLang.我对 GoLang 中的二维数组有疑问。 I do not know why the sort method I use does not work, but It works well in java, C, and C++, but I am not sure what is wrong when I applied the same sort method in Golang, sometimes it give me the right result, sometimes, it does not sort at all.我不知道为什么我使用的排序方法不起作用,但它在 java、C 和 C++ 中运行良好,但我不确定在 Golang 中应用相同的排序方法时有什么问题,有时它会给我正确的结果,有时,它根本不排序。 Please help.请帮忙。 Thank you so much in advance.非常感谢你提前。

package main

import (
   "fmt"
)

var employee int = 0
var day int = 1

func main() {

   list := [][] int {{2, 4, 3, 4, 5, 8, 8},
                     {7, 3, 4, 3, 3, 4, 4},
                     {3, 3, 4, 3, 3, 2, 2},
                     {9, 3, 4, 7, 3, 4, 1},
                     {3, 5, 4, 3, 6, 3, 8},
                     {3, 4, 4, 6, 3, 4, 4},
                     {3, 7, 4, 8, 3, 8, 4},
                     {6, 3, 5, 9, 2, 7, 9}}

   var result [8][2] int 

   for i := 0; i < len(result); i++ {

       var total int = 0

       for j := 0; j < len(list[i]); j++ {
          total += list[i][j]
       }

       result[i][employee] = i 
       result[i][day] = total
   }

   sort(result)

   fmt.Println("The decreasing order is:")

   for i := 0; i < len(result); i++ {

       fmt.Printf("Employee %v's total dayoff is %v\n", result[i][employee], result[i][day])
    }
}

func sort(list[8][2] int) {

    for i := 0; i < len(list); i++ {

        var max_day int = list[i][day]
        var max_employee int = list[i][employee]
        var max_index int = i 

        for j := i + 1; j < len(list); j++ {

            if list[j][day] > max_day {
                max_day = list[j][day]
                max_employee = list[j][employee]
                max_index = j
            }
        }

        if max_index != i {
            list[max_index][employee] = list[i][employee]
            list[max_index][day] = list[i][day]
            list[i][employee] = max_employee
            list[i][day] = max_day
        }
    }
}

You're modifying a copy of list in your sort() function, change its prototype to:您正在sort() function 中修改list的副本,将其原型更改为:

func sort(list *[8][2]int) {

and call it:并称之为:

sort(&result)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM