Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort integer array in golang using default sort function

Tags:

sorting

go

A stupid question. I can't sort using default sort function in go

    package main
    import "fmt"
    import "sort"
    func main(){
            var arr [5]int
            fmt.Println("Enter 5 elements")
            for i:=0;i<5;i++{
                    fmt.Scanf("%d",&arr[i])
            }
            sort.Ints(arr)
            fmt.Println(arr)
    }

When executing the above program, It throws out

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

Need Help.

like image 497
Jose Thomas Avatar asked Aug 30 '16 04:08

Jose Thomas


1 Answers

sort.Ints expects a slice of int, not an array. Easiest fix is to change

sort.Ints(arr)

to

sort.Ints(arr[:])
like image 177
sberry Avatar answered Oct 05 '22 07:10

sberry