Download this file
| 1 | package mapa |
| 2 | |
| 3 | // topK is the count best of items, best first, by less. It keeps a |
| 4 | // sorted window and rejects most items with one comparison, so choosing |
| 5 | // 8 results from 10,000 candidates never sorts the 10,000. |
| 6 | func topK[T any](items []T, count int, less func(T, T) bool) []T { |
| 7 | if count <= 0 { |
| 8 | return nil |
| 9 | } |
| 10 | best := make([]T, 0, count+1) |
| 11 | for _, item := range items { |
| 12 | if len(best) == count && !less(item, best[count-1]) { |
| 13 | continue |
| 14 | } |
| 15 | at := len(best) |
| 16 | for at > 0 && less(item, best[at-1]) { |
| 17 | at-- |
| 18 | } |
| 19 | best = append(best, item) |
| 20 | copy(best[at+1:], best[at:]) |
| 21 | best[at] = item |
| 22 | if len(best) > count { |
| 23 | best = best[:count] |
| 24 | } |
| 25 | } |
| 26 | return best |
| 27 | } |
| 28 | |