Logo

Programming-Idioms

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

Idiom #28 Sort by a property

Sort the elements of the list (or array-like collection) items in ascending order of x.p, where p is a field of the type Item of the objects in items.

import "sort"
type ItemPSorter []Item
func (s ItemPSorter) Len() int{ return len(s) }
func (s ItemPSorter) Less(i,j int) bool{ return s[i].p<s[j].p }
func (s ItemPSorter) Swap(i,j int) { s[i],s[j] = s[j],s[i] }

func sortItems(items []Item){
	sorter := ItemPSorter(items)
	sort.Sort(sorter)
}

The standard way is to declare a new type ItemSorter as a slice of Item, and carefully implement method Less.
import "slices"
import "cmp"
compare := func(a, b Item) int {
	return cmp.Compare(a.p, b.p)
}
slices.SortFunc(items, compare)

SortFunc is generic and type-safe at compile time.
import "sort"
less := func(i, j int) bool {
	return items[i].p < items[j].p
}
sort.Slice(items, less)

This is the diomatic way since Go 1.8.
with Ada.Containers.Vectors;
use Ada.Containers;
declare
   function Compare_Function (Left, Right : Item) return Boolean is (Left.P < Right.P);
   
   package Item_Vector_Sorting is new Item_Vectors.Generic_Sorting (Compare_Function);

   use Item_Vector_Sorting;
begin
   Sort (Items);
end;

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