-
Notifications
You must be signed in to change notification settings - Fork 5
/
sort.go
56 lines (46 loc) · 1.28 KB
/
sort.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
// Fact sorting is done using the Timsort algorithm which is hybrid
// algorithm of merge sort and insertion sort. This is chosen because facts
// are generally partially sorted by entity since facts are derived from higher
// level objects.
//
// For comparison, comparators for the default Quicksort algorithm
// are implemented for benchmarking purposes.
//
// Wikipedia: https://en.wikipedia.org/wiki/Timsort
// Comparison to quicksort: http://stackoverflow.com/a/19587279/407954
package origins
import (
"sort"
"github.com/psilva261/timsort"
)
// sortBy implements the sort.Interface to support sorting facts
// in place given a comparator.
type sortBy struct {
facts Facts
comp Comparator
}
func (s *sortBy) Len() int {
return len(s.facts)
}
func (s *sortBy) Swap(i, j int) {
s.facts[i], s.facts[j] = s.facts[j], s.facts[i]
}
func (s *sortBy) Less(i, j int) bool {
return s.comp(s.facts[i], s.facts[j])
}
// Sort performs an in-place sort of the facts using the built-in sort method.
func Sort(facts Facts, comp Comparator) {
s := sortBy{
facts: facts,
comp: comp,
}
sort.Sort(&s)
}
// Timsort performs an in-place sort of the facts using the Timsort algorithm.
func Timsort(facts Facts, comp Comparator) {
s := sortBy{
facts: facts,
comp: comp,
}
timsort.TimSort(&s)
}