gitee.com/quant1x/num@v0.3.2/internal/partial/sort.go (about) 1 package partial 2 3 import ( 4 "cmp" 5 "slices" 6 ) 7 8 // Sort partially sorts a slice of any ordered type in ascending order. 9 // Only elements in x[:k] will be in sorted order. This is faster than using 10 // slices.Sort when k is small relative to the number of elements. 11 func Sort[E cmp.Ordered](x []E, k int) { 12 k = __min(k, len(x)) 13 if k > 0 { 14 floydRivest(x, 0, len(x)-1, k-1) // 0-indexed 15 slices.Sort(x[:k-1]) 16 } 17 } 18 19 // SortFunc partially sorts the slice x in ascending order as determined by the 20 // less function. Only elements in x[:k] will be in sorted order. This is faster 21 // than using slices.SortFunc when k is small relative to the number of elements. 22 func SortFunc[E any](x []E, k int, cmp func(E, E) int) { 23 k = __min(k, len(x)) 24 if k > 0 { 25 floydRivestFunc(x, 0, len(x)-1, k-1, cmp) 26 slices.SortFunc(x[:k-1], cmp) 27 } 28 }