Hello, I’m learning Go by doing some exercises, I have this exercise where I should sort numbers from an input and use Go Routines, so let’s don’t talk about the purpose or my algorithm, it’s just exploration.
I’ll explain my problem in the buttom
Here is my code, you cannot use it on Google Playground since my code require some inputs.
package main
import (
"fmt"
"sort"
)
func divideList(list []int, cut int) (tmp, s []int) {
tmp = append(list[cut:])
s = append(list[:cut])
return tmp, s
}
func sortList(list []int, c chan []int) {
sort.Ints(list)
c <- list
}
func main() {
// define the size of the number we want to sort
size := 5
// put the number list into a slice
list := []int{-9, -11, 12, 13, 9}
fmt.Println("Your digits input : ", list)
// divide the number list into 4 different slices
cut := size / 4
list, s1 := divideList(list, cut)
cut = len(list) / 3
list, s2 := divideList(list, cut)
cut = len(list) / 2
list, s3 := divideList(list, cut)
s4 := list
// sort in different go routines
c := make(chan []int, 4)
go sortList(s1, c)
go sortList(s2, c)
go sortList(s3, c)
go sortList(s4, c)
sortedS1 := <-c
sortedS2 := <-c
sortedS3 := <-c
sortedS4 := <-c
fmt.Println(sortedS1)
fmt.Println(sortedS2)
fmt.Println(sortedS3)
fmt.Println(sortedS4)
fmt.Println("-----------------------")
// merge the 4 sorted slices
sortedList1 := append(sortedS1, sortedS2...)
fmt.Println(sortedList1)
sortedList2 := append(sortedS3, sortedS4...)
fmt.Println(sortedList2)
finalList := append(sortedList1, sortedList2...)
fmt.Println(finalList)
// we need to sort it again
sort.Ints(finalList)
fmt.Println("Here your digits sorted: ", finalList)
}
And here is my result (maybe you should try multiple times to get the problem)
How many integer do you want to sort? 5
Please type all your digits you want to sort and press Enter: -9 -11 12 13 9
Your digits input : [-9 -11 12 13 9]
[-9]
[12]
[9 13]
[-11]
-----------------------
[-9 12]
[9 13 12]
[-9 12 9 13 12]
Here your digits sorted: [-9 9 12 12 13]
Process finished with exit code 0
Look at the part after this comment : // merge the 4 sorted slices
The problem is I am merging 4 slices, since we cannot merge them at once, I merged them by two but I can’t see why my results is different.
For this part the result is ok
sortedList1 := append(sortedS1, sortedS2...)
merging [-9] with [12] and nice I have [-9 12]
but this part
sortedList2 := append(sortedS3, sortedS4...)
I am merging [9 13] with [-11] and I have [9 13 12]
Obviously it merge with another slice but why?
I know it’s not the best algorithm but I need to understand the problem.
This happned to me using Goland on Windows, I prefer largely to work on linux but I am trying GoLand IDE.
If someone could explain the problem that would be awsome remember that you need to run code multiple time to get the problem, cause sometimes its sort well.