Logo

Programming-Idioms

This language bar is your friend. Select your favorite languages!
  • Go

Idiom #100 Sort by a comparator

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

import "sort"
sort.Slice(items, func(i, j int) bool {
	return c(items[i], items[j])
})

Since Go 1.8, a single func parameter is sufficient to sort a slice.
import "sort"
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)
}

c has type func(Item, Item) bool.
import "slices"
slices.SortFunc(items, c)

SortFunc is generic and type-safe at compile time.
import "sort"
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)
}

ItemsSorter contains c, which can be any comparator decided at runtime.
with Ada.Containers.Vectors;
use Ada.Containers;
type Integer_Comparator is not null access function (Left, Right : Integer) return Boolean;
      
package Integer_Vectors is new Vectors (Positive, Integer);
use Integer_Vectors;
      
procedure Sort_Using_Comparator (V : in out Vector; C : Integer_Comparator) is
   package Vector_Sorting is new Generic_Sorting (C.all);
   use Vector_Sorting;
         
begin
   Sort (V);
end Sort_Using_Comparator;

New implementation...
< >
programming-idioms.org