https://github.com/hslam/topk
Package topk finds the top k elements in the collection.
https://github.com/hslam/topk
go golang heap heap-sort min-heap top top-k
Last synced: about 2 months ago
JSON representation
Package topk finds the top k elements in the collection.
- Host: GitHub
- URL: https://github.com/hslam/topk
- Owner: hslam
- License: mit
- Created: 2020-10-24T21:19:20.000Z (over 4 years ago)
- Default Branch: master
- Last Pushed: 2020-12-23T13:07:21.000Z (over 4 years ago)
- Last Synced: 2024-11-13T22:35:43.738Z (6 months ago)
- Topics: go, golang, heap, heap-sort, min-heap, top, top-k
- Language: Go
- Homepage:
- Size: 10.7 KB
- Stars: 3
- Watchers: 2
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
- awesome-golang-repositories - topk
README
# topk
[](https://pkg.go.dev/github.com/hslam/topk)
[](https://github.com/hslam/topk/actions)
[](https://codecov.io/gh/hslam/topk)
[](https://goreportcard.com/report/github.com/hslam/topk)
[](https://github.com/hslam/topk/blob/master/LICENSE)Package topk finds the top k elements in the collection.
## Feature
* Min Heap
* Top K
* Sort Top K## Get started
### Install
```
go get github.com/hslam/topk
```
### Import
```
import "github.com/hslam/topk"
```
### Usage
#### Example
```go
package mainimport (
"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])
}
```#### Output
```
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]
```### License
This package is licensed under a MIT license (Copyright (c) 2020 Meng Huang)### Author
topk was written by Meng Huang.