记录一下go实现多重排序的方法和实现堆排序的方式
实现sort接口即可用sort.Sort()方法对对象进行排序,而多重排序呢,我想传入不同排序规则,然后让该对象依次执行不同规则
// 排序规则
type lessFunc func(p1, p2 *CurriculumElem) bool
// MultiSorter 多重排序处理器
type MultiSorter struct {
changes []*CurriculumElem
less []lessFunc
}
// Sort 排序
func (ms *MultiSorter) Sort(changes []*CurriculumElem) {
ms.changes = changes
sort.Sort(ms)
}
// OrderedBy 排序规则
func OrderedBy(less ...lessFunc) *MultiSorter {
return &MultiSorter{
less: less,
}
}
// Len 长度
func (ms *MultiSorter) Len() int {
return len(ms.changes)
}
// Swap 交换
func (ms *MultiSorter) Swap(i, j int) {
ms.changes[i], ms.changes[j] = ms.changes[j], ms.changes[i]
}
// Less 比较
func (ms *MultiSorter) Less(i, j int) bool {
p, q := ms.changes[i], ms.changes[j]
var k int
for k = 0; k < len(ms.less)-1; k++ {
less := ms.less[k]
switch {
case less(p, q):
return true
case less(q, p):
return false
}
}
return ms.less[k](p, q)
}
堆排序也是实现相关接口,然后调用heap包的方法就可以了
func Test01(t *testing.T) {
h := &IntHeap{3, 2, 5}
heap.Init(h)
heap.Push(h, 1)
for h.Len() != 0 {
fmt.Println(heap.Pop(h))
}
}
type IntHeap []int
func (h IntHeap) Swap(i, j int) {
h[i], h[j] = h[j], h[i]
}
func (h IntHeap) Len() int {
return len(h)
}
func (h IntHeap) Less(i, j int) bool {
return h[i] < h[j]
}
func (h *IntHeap) Push(x interface{}) {
*h = append(*h, x.(int))
}
func (h *IntHeap) Pop() interface{} {
old := *h
n := len(old)
x := old[n-1]
*h = old[0 : n-1]
return x
}