Logo

Programming-Idioms

History of Idiom 28 > diff from v19 to v20

Edit summary for version 20 by :

Version 19

2015-09-04, 12:36:57

Version 20

2015-10-29, 14:05:13

Idiom #28 Sort by a property

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

Idiom #28 Sort by a property

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

Code
@items = sort { $a->{p} cmp $b->{p} } @items;
Code
@items = sort { $a->{p} cmp $b->{p} } @items;
Comments bubble
sort gives your code block two items to sort: $a and $b. Two operators are commonly used: cmp to sort lexically, and <=> to sort numerically. Swapping the positions of $a and $b reverses the sort direction.
Comments bubble
sort gives your code block two items to sort: $a and $b. Two operators are commonly used: cmp to sort lexically, and <=> to sort numerically. Swapping the positions of $a and $b reverses the sort direction.
Imports
import "sort"
Imports
import "sort"
Code
type ItemPSorter []Item
func (this ItemPSorter) Len() int{ return len(this) }
func (this ItemPSorter) Less(i,j int) bool{ return this[i].p<this[j].p }
func (this ItemPSorter) Swap(i,j int) { this[i],this[j] = this[j],this[i] }

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

func sortItems(items []Item){
	sorter := ItemPSorter(items)
	sort.Sort( sorter )
}
Comments bubble
The standard way is to declare a new type ItemSorter as a slice of Item, and carefully implement method Less.
Comments bubble
The standard way is to declare a new type ItemSorter as a slice of Item, and carefully implement method Less.
Demo URL
http://play.golang.org/p/WGjE22-hDV
Demo URL
http://play.golang.org/p/WGjE22-hDV
Imports
import java.util.Arrays;
import java.util.Comparator;
Imports
import java.util.Arrays;
import java.util.Comparator;
Code
Arrays.sort(items, new Comparator<Item>(){
	public int compare(Item a, Item b){
		return a.birth - b.birth;
	}
});
Code
Arrays.sort(items, new Comparator<Item>(){
	public int compare(Item a, Item b){
		return a.birth - b.birth;
	}
});
Comments bubble
items is an array of type Item[].
Use an anonymous class which implements Comparator<Item>
Comments bubble
items is an array of type Item[].
Use an anonymous class which implements Comparator<Item>
Demo URL
http://ideone.com/gqNVEH
Demo URL
http://ideone.com/gqNVEH