Package topk finds the top k elements in the collection.
- Min Heap
- Top K
- Sort Top K
go get github.com/hslam/topk
import "github.com/hslam/topk"
package main
import (
"fmt"
"github.com/hslam/topk"
)
type list []int
func (h list) Len() int { return len(h) }
func (h list) Less(i, j int) bool { return h[i] < h[j] }
func (h list) Swap(i, j int) { h[i], h[j] = h[j], h[i] }
func main() {
Top(list{5, 10, 2, 7, 1}, 3, false)
Top(list{5, 10, 2, 7, 1}, 3, true)
}
func Top(l list, k int, sortK bool) {
fmt.Printf("list:%v,k:%d,sortK:%t\t", l, k, sortK)
topk.Top(l, k, sortK)
fmt.Printf("==>\ttop%d:%v\n", k, l[:k])
}
list:[5 10 2 7 1],k:3,sortK:false ==> top3:[5 10 7]
list:[5 10 2 7 1],k:3,sortK:true ==> top3:[10 7 5]
This package is licensed under a MIT license (Copyright (c) 2020 Meng Huang)
topk was written by Meng Huang.