Logo

Programming-Idioms

History of Idiom 100 > diff from v4 to v5

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

Version 4

2015-12-22, 15:40:50

Version 5

2015-12-22, 15:47:32

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