Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
220 views
in Technique[技术] by (71.8m points)

How do I reverse sort a slice of integer Go?

I am trying to reverse-sort a slice of integers in Go.

  example := []int{1,25,3,5,4}
  sort.Ints(example) // this will give me a slice sorted from 1 to the highest number

How do I sort it so that it goes from highest to lowest? so [25 5 4 3 1]

I have tried this

sort.Sort(sort.Reverse(sort.Ints(keys)))

Source: http://golang.org/pkg/sort/#Reverse

However, I am getting the error below

# command-line-arguments
./Roman_Numerals.go:31: sort.Ints(keys) used as value
question from:https://stackoverflow.com/questions/18343208/how-do-i-reverse-sort-a-slice-of-integer-go

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

sort.Ints is a convenient function to sort a couple of ints. Generally you need to implement the sort.Interface interface if you want to sort something and sort.Reverse just returns a different implementation of that interface that redefines the Less method.

Luckily the sort package contains a predefined type called IntSlice that implements sort.Interface:

keys := []int{3, 2, 8, 1}
sort.Sort(sort.Reverse(sort.IntSlice(keys)))
fmt.Println(keys)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...