Sort using a custom comparator: Difference between revisions

Go solution
m (→‎{{header|PARI/GP}}: descending)
(Go solution)
Line 563:
Output:
<pre>["strings"; "sample"; "sorted"; "Here"; "some"; "are"; "be"; "to"]</pre>
=={{header|Go}}==
<lang go>package main
 
import ("fmt"; "sort")
 
type sortable struct {
strs []string
less func(string, string) bool
}
 
func (s sortable) Len() int {return len(s.strs)}
func (s sortable) Swap(i, j int) {s.strs[i], s.strs[j] = s.strs[j], s.strs[i]}
func (s sortable) Less(i, j int) bool {return s.less(s.strs[i], s.strs[j])}
 
func main() {
var s sortable
s.strs = []string{"to", "an", "admiring", "bog"}
fmt.Println(s.strs, "(original)")
 
s.less = func(a, b string) bool { return len(a) > len(b) }
sort.Sort(s)
fmt.Println(s.strs, "(descending string length)")
 
s.less = func(a, b string) bool { return a < b }
sort.Sort(s)
fmt.Println(s.strs, "(ascending lexicographic)")
}</lang>
Output:
<pre>[to an admiring bog] (original)
[admiring bog to an] (descending string length)
[admiring an bog to] (ascending lexicographic)</pre>
 
=={{header|Groovy}}==
1,707

edits