Logo

Programming-Idioms

History of Idiom 100 > diff from v11 to v12

Edit summary for version 12 by :
[Go] +DocURL to package sort

Version 11

2015-12-27, 17:10:13

Version 12

2015-12-30, 16:58:40

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 (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)
}
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
Demo URL
http://play.golang.org/p/1cJqFz0kbS
Demo URL
http://play.golang.org/p/1cJqFz0kbS