Question about sorting 2 dimensional array in Golang

75 Views Asked by At

I have a question about 2 dimensional array in 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. 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
        }
    }
}
1

There are 1 best solutions below

2
Arkadiusz Drabczyk On

You're modifying a copy of list in your sort() function, change its prototype to:

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

and call it:

sort(&result)