github.com/searKing/golang/go@v1.2.117/sort/partialsort.go (about) 1 // Copyright 2023 The searKing Author. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package sort 6 7 import ( 8 "sort" 9 10 "github.com/searKing/golang/go/exp/math" 11 ) 12 13 type partial struct { 14 // This embedded Interface permits Partial to use the methods of 15 // another Interface implementation. 16 sort.Interface 17 18 Size int 19 } 20 21 // Len returns the opposite of the embedded implementation's Len method. 22 func (r partial) Len() int { 23 return math.Min(r.Size, r.Interface.Len()) 24 } 25 26 // IsPartialSorted reports whether data[:k] is partial sorted, as top k of data[:]. 27 func IsPartialSorted(data sort.Interface, k int) bool { 28 if k >= data.Len() { 29 return sort.IsSorted(data) 30 } 31 32 // data[:k] sorted 33 if !sort.IsSorted(&partial{data, k}) { 34 return false 35 } 36 // data[k-1] < any element in data[k:] 37 n := data.Len() 38 for i := k; i < n; i++ { 39 if data.Less(i, k-1) { 40 return false 41 } 42 } 43 return true 44 }