本文整理汇总了Golang中sort.Search函数的典型用法代码示例。如果您正苦于以下问题:Golang Search函数的具体用法?Golang Search怎么用?Golang Search使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Search函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: main
func main() {
v := make([]T, 100)
for i := 0; i < L; i++ {
a := i * 10
b := a + 9
v[i] = T{L: a, H: b}
}
// mix them up
for i := range v {
j := rand.Intn(i + 1)
v[i], v[j] = v[j], v[i]
}
fmt.Printf("\n%v\n", v)
// sort them
sort.Sort(TS(v))
fmt.Printf("\n%v\n", v)
// search
k := sort.Search(len(v), func(i int) bool { return v[i].H >= 321 })
fmt.Printf("%d: %v\n", k, v[k])
k = sort.Search(len(v), func(i int) bool { return v[i].H >= 118 })
fmt.Printf("%d: %v\n", k, v[k])
// need to make sure the thing you are looking for isn't bigger than
// the last thing and smaller than the first (Go panics on out-of-range)
}
示例2: idxsearch
func (pisearch *Pisearch) idxsearch(start int, searchkey []byte) (found bool, position int) {
i := sort.Search(pisearch.numDigits, func(i int) bool {
return pisearch.compare(pisearch.idxAt(i), searchkey) >= 0
})
j := i + sort.Search(pisearch.numDigits-i, func(j int) bool {
return pisearch.compare(pisearch.idxAt(j+i), searchkey) != 0
})
//fmt.Println("Compare got i: ", i, "j", j)
//fmt.Println("Digits there: ", pisearch.GetDigits(pisearch.idxAt(i), len(searchkey)))
nMatches := (j - i)
var positions []int
for ; i < j; i++ {
positions = append(positions, pisearch.idxAt(i))
}
if nMatches > 1 {
sort.Ints(positions)
}
for i := 0; i < nMatches; i++ {
if positions[i] >= start {
return true, positions[i]
}
}
return false, 0
}
示例3: getShardRange
func (self *ClusterConfiguration) getShardRange(querySpec QuerySpec, shards []*ShardData) []*ShardData {
if querySpec.AllShardsQuery() {
return shards
}
startTime := common.TimeToMicroseconds(querySpec.GetStartTime())
endTime := common.TimeToMicroseconds(querySpec.GetEndTime())
// the shards are always in descending order, if we have the following shards
// [t + 20, t + 30], [t + 10, t + 20], [t, t + 10]
// if we are querying [t + 5, t + 15], we have to find the first shard whose
// startMicro is less than the end time of the query,
// which is the second shard [t + 10, t + 20], then
// start searching from this shard for the shard that has
// endMicro less than the start time of the query, which is
// no entry (sort.Search will return the length of the slice
// in this case) so we return [t + 10, t + 20], [t, t + 10]
// as expected
startIndex := sort.Search(len(shards), func(n int) bool {
return shards[n].startMicro < endTime
})
if startIndex == len(shards) {
return nil
}
endIndex := sort.Search(len(shards)-startIndex, func(n int) bool {
return shards[n+startIndex].endMicro <= startTime
})
return shards[startIndex : endIndex+startIndex]
}
示例4: preloadChunksForRange
// preloadChunksForRange loads chunks for the given range from the persistence.
// The caller must have locked the fingerprint of the series.
func (s *memorySeries) preloadChunksForRange(
fp model.Fingerprint,
from model.Time, through model.Time,
mss *MemorySeriesStorage,
) (SeriesIterator, error) {
firstChunkDescTime := model.Latest
if len(s.chunkDescs) > 0 {
firstChunkDescTime = s.chunkDescs[0].FirstTime()
}
if s.chunkDescsOffset != 0 && from.Before(firstChunkDescTime) {
cds, err := mss.loadChunkDescs(fp, s.persistWatermark)
if err != nil {
return nopIter, err
}
s.chunkDescs = append(cds, s.chunkDescs...)
s.chunkDescsOffset = 0
s.persistWatermark += len(cds)
firstChunkDescTime = s.chunkDescs[0].FirstTime()
}
if len(s.chunkDescs) == 0 || through.Before(firstChunkDescTime) {
return nopIter, nil
}
// Find first chunk with start time after "from".
fromIdx := sort.Search(len(s.chunkDescs), func(i int) bool {
return s.chunkDescs[i].FirstTime().After(from)
})
// Find first chunk with start time after "through".
throughIdx := sort.Search(len(s.chunkDescs), func(i int) bool {
return s.chunkDescs[i].FirstTime().After(through)
})
if fromIdx == len(s.chunkDescs) {
// Even the last chunk starts before "from". Find out if the
// series ends before "from" and we don't need to do anything.
lt, err := s.chunkDescs[len(s.chunkDescs)-1].LastTime()
if err != nil {
return nopIter, err
}
if lt.Before(from) {
return nopIter, nil
}
}
if fromIdx > 0 {
fromIdx--
}
if throughIdx == len(s.chunkDescs) {
throughIdx--
}
if fromIdx > throughIdx {
// Guard against nonsensical result. The caller will quarantine the series with a meaningful log entry.
return nopIter, fmt.Errorf("fromIdx=%d is greater than throughIdx=%d, likely caused by data corruption", fromIdx, throughIdx)
}
pinIndexes := make([]int, 0, throughIdx-fromIdx+1)
for i := fromIdx; i <= throughIdx; i++ {
pinIndexes = append(pinIndexes, i)
}
return s.preloadChunks(pinIndexes, fp, mss)
}
示例5: ExtractSamples
func (g *getValuesAlongRangeOp) ExtractSamples(in metric.Values) (out metric.Values) {
if len(in) == 0 {
return
}
// Find the first sample where time >= g.current.
firstIdx := sort.Search(len(in), func(i int) bool {
return !in[i].Timestamp.Before(g.current)
})
if firstIdx == len(in) {
// No samples at or after operator start time. This can only
// happen if we try applying the operator to a time after the
// last recorded sample. In this case, we're finished.
g.current = g.through.Add(clientmodel.MinimumTick)
return
}
// Find the first sample where time > g.through.
lastIdx := sort.Search(len(in), func(i int) bool {
return in[i].Timestamp.After(g.through)
})
if lastIdx == firstIdx {
g.current = g.through.Add(clientmodel.MinimumTick)
return
}
lastSampleTime := in[lastIdx-1].Timestamp
// Sample times are stored with a maximum time resolution of one second,
// so we have to add exactly that to target the next chunk on the next
// op iteration.
g.current = lastSampleTime.Add(time.Second)
return in[firstIdx:lastIdx]
}
示例6: main
func main() {
files := []string{"Remco", "clara", "Willem", "pieter"}
target := "Clara"
fmt.Printf("Looking for %s in %q\n", target, files)
sort.Strings(files)
compareSimple := func(i int) bool { return files[i] >= target }
i := sort.Search(len(files), compareSimple)
if i < len(files) && files[i] == target {
fmt.Printf("Found \"%s\" at files[%d]\n", files[i], i)
} else {
fmt.Printf("Did not find \"%s\".\n", target)
}
SortFoldedStrings(files)
fmt.Printf("Looking for %s in %q\n", target, files)
betterCompare := func(i int) bool {
return strings.ToLower(files[i]) >= strings.ToLower(target)
}
i = sort.Search(len(files), betterCompare)
if i < len(files) && strings.EqualFold(files[i], target) {
fmt.Printf("Found \"%s\" at files[%d]\n", files[i], i)
} else {
fmt.Printf("Did not find \"%s\".\n", target)
}
}
示例7: Split
func Split(a Assembly, begin, end int) (b, c Assembly) {
sort.Sort(a)
// find the first fragment, which begin index is in
idxL := sort.Search(len(a), func(i int) bool { return a[i].End >= begin })
idxR := sort.Search(len(a), func(i int) bool { return a[i].Begin > end })
for i, _ := range a {
if i >= idxL && i < idxR {
if begin <= a[i].Begin {
begin = a[i].Begin
} else {
b = append(b, Fragment{Begin: a[i].Begin, End: begin - 1})
}
if end >= a[i].End {
c = append(c, Fragment{Begin: begin, End: a[i].End})
} else {
c = append(c, Fragment{Begin: begin, End: end})
b = append(b, Fragment{Begin: end + 1, End: a[i].End})
}
} else {
b = append(b, a[i])
}
}
return
}
示例8: findLeafInOrderedSequence
// Returns a cursor to |key| in |ms|, plus the leaf + index that |key| is in. |t| is the type of the ordered values.
func findLeafInOrderedSequence(ms metaSequence, t Type, key Value, getValues getLeafOrderedValuesFn, vr ValueReader) (cursor *sequenceCursor, leaf Value, idx int) {
cursor, leaf = newMetaSequenceCursor(ms, vr)
if isSequenceOrderedByIndexedType(t) {
orderedKey := key.(OrderedValue)
cursor.seekBinary(func(mt sequenceItem) bool {
return !mt.(metaTuple).value.(OrderedValue).Less(orderedKey)
})
} else {
cursor.seekBinary(func(mt sequenceItem) bool {
return !mt.(metaTuple).value.(Ref).TargetRef().Less(key.Ref())
})
}
if current := cursor.current().(metaTuple); current.ChildRef().TargetRef() != valueFromType(leaf, leaf.Type()).Ref() {
leaf = readMetaTupleValue(current, vr)
}
if leafData := getValues(leaf); isSequenceOrderedByIndexedType(t) {
orderedKey := key.(OrderedValue)
idx = sort.Search(len(leafData), func(i int) bool {
return !leafData[i].(OrderedValue).Less(orderedKey)
})
} else {
idx = sort.Search(len(leafData), func(i int) bool {
return !leafData[i].Ref().Less(key.Ref())
})
}
return
}
示例9: splitRangeByPrefixes
// splitRangeByPrefixes returns a list of key ranges with
// corresponding configs. The split is done using matching prefix
// config entries. For example, consider the following set of configs
// and prefixes:
//
// /: config1
// /db1: config2
//
// A range containing keys from /0 - /db3 will map to
// the following split ranges and corresponding configs:
//
// /0 - /db1: config1
// /db1 - /db2: config2
// /db2 - /db3: config1
//
// After calling prefixConfigMap.build(), our prefixes will look
// like:
//
// /: config1
// /db1: config2
// /db2: config1
//
// The algorithm is straightforward for splitting a range by existing
// prefixes. Lookup start key; that is first config. Lookup end key:
// that is last config. We then step through the intervening
// prefixConfig records and create a rangeResult for each.
func (p *prefixConfigMap) splitRangeByPrefixes(start, end Key) ([]*rangeResult, error) {
if bytes.Compare(start, end) >= 0 {
return nil, util.Errorf("start key %q not less than end key %q", start, end)
}
startIdx := sort.Search(len(p.configs), func(i int) bool {
return bytes.Compare(start, p.configs[i].prefix) < 0
})
endIdx := sort.Search(len(p.configs), func(i int) bool {
return bytes.Compare(end, p.configs[i].prefix) < 0
})
if startIdx >= len(p.configs) || endIdx > len(p.configs) {
return nil, util.Errorf("start and/or end keys (%q, %q) fall outside prefix range; "+
"was default prefix not added?", start, end)
}
// Create the first range result which goes from start -> end and
// uses the config specified for the start key.
var results []*rangeResult
result := &rangeResult{start: start, end: end, config: p.configs[startIdx-1].config}
results = append(results, result)
// Now, cycle through from startIdx to endIdx, adding a new
// rangeResult at each step.
for i := startIdx; i < endIdx; i++ {
result.end = p.configs[i].prefix
if bytes.Compare(result.end, end) == 0 {
break
}
result = &rangeResult{start: result.end, end: end, config: p.configs[i].config}
results = append(results, result)
}
return results, nil
}
示例10: Length
// Length iterates over the mutation layer and counts number of elements.
func (l *List) Length(afterUid uint64) int {
l.RLock()
defer l.RUnlock()
pidx, midx := 0, 0
pl := l.getPostingList(0)
if afterUid > 0 {
pidx = sort.Search(len(pl.Postings), func(idx int) bool {
p := pl.Postings[idx]
return afterUid < p.Uid
})
midx = sort.Search(len(l.mlayer), func(idx int) bool {
mp := l.mlayer[idx]
return afterUid < mp.Uid
})
}
count := len(pl.Postings) - pidx
for _, p := range l.mlayer[midx:] {
if p.Op == Add {
count++
} else if p.Op == Del {
count--
}
}
return count
}
示例11: lookup
// lookup returns the smallest index of an entry with an exact match
// for name, or an inexact match starting with name/. If there is no
// such entry, the result is -1, false.
func (z zipList) lookup(name string) (index int, exact bool) {
// look for exact match first (name comes before name/ in z)
i := sort.Search(len(z), func(i int) bool {
return name <= z[i].Name
})
if i >= len(z) {
return -1, false
}
// 0 <= i < len(z)
if z[i].Name == name {
return i, true
}
// look for inexact match (must be in z[i:], if present)
z = z[i:]
name += "/"
j := sort.Search(len(z), func(i int) bool {
return name <= z[i].Name
})
if j >= len(z) {
return -1, false
}
// 0 <= j < len(z)
if strings.HasPrefix(z[j].Name, name) {
return i + j, false
}
return -1, false
}
示例12: DeleteColumns
func (w *MockWriter) DeleteColumns(cf string, key []byte, columns [][]byte) Writer {
rows := w.pool.Rows(cf)
t := now()
i := sort.Search(len(rows), func(i int) bool { return bytes.Compare(rows[i].Key, key) >= 0 })
if i < len(rows) && bytes.Equal(rows[i].Key, key) {
// Row exists, delete the columns
e := rows[i]
cols := e.Columns
for _, c := range columns {
j := sort.Search(len(cols), func(j int) bool { return bytes.Compare(cols[j].Name, c) >= 0 })
if j < len(cols) && bytes.Equal(cols[j].Name, c) {
if t >= cols[j].Timestamp {
// TODO store tombstone?
copy(cols[j:], cols[j+1:])
cols[len(cols)-1] = nil
cols = cols[:len(cols)-1]
}
}
}
e.Columns = cols
}
return w
}
示例13: Add
// Adds an element to the start of the buffer (removing one from the end if necessary).
func (self *TimedStore) Add(timestamp time.Time, item interface{}) {
data := timedStoreData{
timestamp: timestamp,
data: item,
}
// Common case: data is added in order.
if len(self.buffer) == 0 || !timestamp.Before(self.buffer[len(self.buffer)-1].timestamp) {
self.buffer = append(self.buffer, data)
} else {
// Data is out of order; insert it in the correct position.
index := sort.Search(len(self.buffer), func(index int) bool {
return self.buffer[index].timestamp.After(timestamp)
})
self.buffer = append(self.buffer, timedStoreData{}) // Make room to shift the elements
copy(self.buffer[index+1:], self.buffer[index:]) // Shift the elements over
self.buffer[index] = data
}
// Remove any elements before eviction time.
// TODO(rjnagal): This is assuming that the added entry has timestamp close to now.
evictTime := timestamp.Add(-self.age)
index := sort.Search(len(self.buffer), func(index int) bool {
return self.buffer[index].timestamp.After(evictTime)
})
if index < len(self.buffer) {
self.buffer = self.buffer[index:]
}
// Remove any elements if over our max size.
if self.maxItems >= 0 && len(self.buffer) > self.maxItems {
startIndex := len(self.buffer) - self.maxItems
self.buffer = self.buffer[startIndex:]
}
}
示例14: ActualRange
func (s *Stock) ActualRange(startDate time.Time, endDate time.Time, overrideUrl string) (Span, error) {
// Check if data is memoized in s.Span, if so return that subslice.
if s.Span.Covers(startDate) && s.Span.Covers(endDate) {
// Find the first date after startDate in Span. The smallest range that
// includes startDate begins at that date - 1
start := sort.Search(len(s.Span), func(i int) bool { return s.Span[i].Time.After(startDate) }) - 1
end := sort.Search(len(s.Span), func(i int) bool { return s.Span[i].Time.After(endDate) })
return s.Span[start:end], nil
}
// all or part of the data is missing from what is memoized, check the database
dbSpan, err := DB.GetRange(s, startDate, endDate)
if err != nil {
return nil, err
}
if len(dbSpan) > 0 {
// information was stored in the database, return it
return dbSpan, nil
} else {
// data wasn't in database, populate it
newSpan, err := s.ActualPopulate(startDate, endDate, overrideUrl)
if err != nil {
return nil, err
}
return newSpan, nil
}
}
示例15: Lookup
// Returns the smallest index of an entry with an exact match for "name",
// or an inexact match starting with "name/". If there is no such entry,
// returns (-1, false).
func (zl zipList) Lookup(name string) (idx int, exact bool) {
// Look for exact match.
// "name" comes before "name/" in zl.
i := sort.Search(len(zl), func(i int) bool {
return name <= zl[i].f.Name
})
if i >= len(zl) {
return -1, false
}
if zl[i].f.Name == name {
return i, true
}
// Look for inexact match in zl[i:].
zl = zl[i:]
name += "/"
j := sort.Search(len(zl), func(i int) bool {
return name <= zl[i].f.Name
})
if j >= len(zl) {
return -1, false
}
// 0 <= j < len(zl)
if strings.HasPrefix(zl[j].f.Name, name) {
return i + j, false
}
return -1, false
}