Logo

Programming-Idioms

History of Idiom 100 > diff from v27 to v28

Edit summary for version 28 by programming-idioms.org:
New Go implementation by user [programming-idioms.org]

Version 27

2016-11-13, 14:59:55

Version 28

2016-12-11, 20:22:39

Idiom #100 Sort by a comparator

Sort elements of array-like collection items, using a comparator c.

Idiom #100 Sort by a comparator

Sort elements of array-like collection items, using a comparator c.

Imports
import "sort"
Code
type ItemsSorter struct {
	items []Item
	c     func(x, y Item) bool
}

func (s ItemsSorter) Len() int           { return len(s.items) }
func (s ItemsSorter) Less(i, j int) bool { return s.c(s.items[i], s.items[j]) }
func (s ItemsSorter) Swap(i, j int)      { s.items[i], s.items[j] = s.items[j], s.items[i] }

func sortItems(items []Item, c func(x, y Item) bool) {
	sorter := ItemsSorter{
		items,
		c,
	}
	sort.Sort(sorter)
}
Comments bubble
ItemsSorter contains c, which can be any comparator decided at runtime.
Doc URL
https://golang.org/pkg/sort/#example__sortKeys
Demo URL
https://play.golang.org/p/2Bmn9rwWtK