Logo

Programming-Idioms

History of Idiom 100 > diff from v28 to v29

Edit summary for version 29 by programming-idioms.org:
[Go] this is not an idiomatic name, choosing s instead.

Version 28

2016-12-11, 20:22:39

Version 29

2016-12-11, 20:24:08

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"
Imports
import "sort"
Code
type ItemCSorter []Item
func (this ItemCSorter) Len() int           { return len(this) }
func (this ItemCSorter) Less(i, j int) bool { return c(this[i], this[j]) }
func (this ItemCSorter) Swap(i, j int)      { this[i], this[j] = this[j], this[i] }

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

func sortItems(items []Item) {
	sorter := ItemCSorter(items)
	sort.Sort(sorter)
}
Comments bubble
c has type func(Item, Item) bool.
Comments bubble
c has type func(Item, Item) bool.
Doc URL
https://golang.org/pkg/sort/#example__sortKeys
Doc URL
https://golang.org/pkg/sort/#example__sortKeys
Demo URL
http://play.golang.org/p/1cJqFz0kbS
Demo URL
https://play.golang.org/p/-AWqAJfq1J