Sort a piece of uint64 in go

I am writing a Go application using Go 1.7rc3.

I have a piece of uint64 ( var dirRange []uint64 ) that I want to sort.

the sort package has a function sort.Ints() , but that requires []int , and I have []uint64 .

what should I do? can i recruit the whole slice?

thanks

+7
slice go
source share
3 answers

Starting with version 1.8, you can use the simpler sort.Slice function. In your case, it will be something like the following:

 sort.Slice(dirRange, func(i, j int) bool { return dirRange[i] < dirRange[j] }) 

This avoids the need to define any type for sorting only.

+3
source share

You can define sort.Interface on dirRange , which can be an alias of type []uint64 :

 type DirRange []uint64 func (a DirRange) Len() int { return len(a) } func (a DirRange) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a DirRange) Less(i, j int) bool { return a[i] < a[j] } func main() { dirRange := DirRange{2, 5, 7, 1, 9, 4} sort.Sort(dirRange) fmt.Println(dirRange) } 

Output:

 [1 2 4 5 7 9] 

This way you can avoid casting and work directly with your array. Since the base type is a []uint64 , you can still use common slice operations. For example:

 dirRange := make(DirRange, 10) dirRange = append(dirRange, 2) 
+6
source share

You can specify an alias of type [] uint64, add standard "template" sorting methods to implement sort.interface ( Len , Swap and Less - https://golang.org/pkg/sort/#Interface ); either create an instance of a new type, or create an existing slice [] of uint64 into a new type, as was done in the following example (also https://play.golang.org/p/BbB3L9TmBI ):

 package main import ( "fmt" "sort" ) type uint64arr []uint64 func (a uint64arr) Len() int { return len(a) } func (a uint64arr) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a uint64arr) Less(i, j int) bool { return a[i] < a[j] } func (a uint64arr) String() (s string) { sep := "" // for printing separating commas for _, el := range a { s += sep sep = ", " s += fmt.Sprintf("%d", el) } return } func main() { dirRange := []uint64{3, 2, 400000} arr := uint64arr(dirRange) sort.Sort(arr) fmt.Printf("%s\n", arr) fmt.Printf("%#v\n", dirRange) } 

Output:

 2, 3, 400000 []uint64{0x2, 0x3, 0x61a80} 

indicating that both arrays are sorted, since the second is an alias with a drive for the original.

-2
source share

All Articles