Logo

Programming-Idioms

History of Idiom 28 > diff from v40 to v41

Edit summary for version 41 by programming-idioms.org:
[Go] gofmt

Version 40

2017-06-02, 15:59:29

Version 41

2018-02-14, 12:52:36

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

Idiom #28 Sort by a property

Sort elements of array-like collection items in ascending order of x.p, where p is a field of the type Item of the objects in items.

Imports
import "sort"
Imports
import "sort"
Code
type ItemPSorter []Item
func (s ItemPSorter) Len() int{ return len(s) }
func (s ItemPSorter) Less(i,j int) bool{ return s[i].p<s[j].p }
func (s ItemPSorter) Swap(i,j int) { s[i],s[j] = s[j],s[i] }

func sortItems(items []Item){
	sorter := ItemPSorter(items)
	sort.Sort( sorter )
}
Code
type ItemPSorter []Item
func (s ItemPSorter) Len() int{ return len(s) }
func (s ItemPSorter) Less(i,j int) bool{ return s[i].p<s[j].p }
func (s ItemPSorter) Swap(i,j int) { s[i],s[j] = s[j],s[i] }

func sortItems(items []Item){
	sorter := ItemPSorter(items)
	sort.Sort(sorter)
}
Comments bubble
The standard way is to declare a new type ItemSorter as a slice of Item, and carefully implement method Less.
Comments bubble
The standard way is to declare a new type ItemSorter as a slice of Item, and carefully implement method Less.
Demo URL
https://play.golang.org/p/t7R2h5kzwJ
Demo URL
https://play.golang.org/p/t7R2h5kzwJ