search.go 4.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. // Copyright 2010 The Go Authors. 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. // This file implements binary search.
  5. package sort
  6. // Search uses binary search to find and return the smallest index i
  7. // in [0, n) at which f(i) is true, assuming that on the range [0, n),
  8. // f(i) == true implies f(i+1) == true. That is, Search requires that
  9. // f is false for some (possibly empty) prefix of the input range [0, n)
  10. // and then true for the (possibly empty) remainder; Search returns
  11. // the first true index. If there is no such index, Search returns n.
  12. // (Note that the "not found" return value is not -1 as in, for instance,
  13. // strings.Index.)
  14. // Search calls f(i) only for i in the range [0, n).
  15. //
  16. // A common use of Search is to find the index i for a value x in
  17. // a sorted, indexable data structure such as an array or slice.
  18. // In this case, the argument f, typically a closure, captures the value
  19. // to be searched for, and how the data structure is indexed and
  20. // ordered.
  21. //
  22. // For instance, given a slice data sorted in ascending order,
  23. // the call Search(len(data), func(i int) bool { return data[i] >= 23 })
  24. // returns the smallest index i such that data[i] >= 23. If the caller
  25. // wants to find whether 23 is in the slice, it must test data[i] == 23
  26. // separately.
  27. //
  28. // Searching data sorted in descending order would use the <=
  29. // operator instead of the >= operator.
  30. //
  31. // To complete the example above, the following code tries to find the value
  32. // x in an integer slice data sorted in ascending order:
  33. //
  34. // x := 23
  35. // i := sort.Search(len(data), func(i int) bool { return data[i] >= x })
  36. // if i < len(data) && data[i] == x {
  37. // // x is present at data[i]
  38. // } else {
  39. // // x is not present in data,
  40. // // but i is the index where it would be inserted.
  41. // }
  42. //
  43. // As a more whimsical example, this program guesses your number:
  44. //
  45. // func GuessingGame() {
  46. // var s string
  47. // fmt.Printf("Pick an integer from 0 to 100.\n")
  48. // answer := sort.Search(100, func(i int) bool {
  49. // fmt.Printf("Is your number <= %d? ", i)
  50. // fmt.Scanf("%s", &s)
  51. // return s != "" && s[0] == 'y'
  52. // })
  53. // fmt.Printf("Your number is %d.\n", answer)
  54. // }
  55. //
  56. func Search(n int, f func(int) bool) int {
  57. // Define f(-1) == false and f(n) == true.
  58. // Invariant: f(i-1) == false, f(j) == true.
  59. i, j := 0, n
  60. for i < j {
  61. h := int(uint(i+j) >> 1) // avoid overflow when computing h
  62. // i ≤ h < j
  63. if !f(h) {
  64. i = h + 1 // preserves f(i-1) == false
  65. } else {
  66. j = h // preserves f(j) == true
  67. }
  68. }
  69. // i == j, f(i-1) == false, and f(j) (= f(i)) == true => answer is i.
  70. return i
  71. }
  72. // Convenience wrappers for common cases.
  73. // SearchInts searches for x in a sorted slice of ints and returns the index
  74. // as specified by Search. The return value is the index to insert x if x is
  75. // not present (it could be len(a)).
  76. // The slice must be sorted in ascending order.
  77. //
  78. func SearchInts(a []int, x int) int {
  79. return Search(len(a), func(i int) bool { return a[i] >= x })
  80. }
  81. // SearchFloat64s searches for x in a sorted slice of float64s and returns the index
  82. // as specified by Search. The return value is the index to insert x if x is not
  83. // present (it could be len(a)).
  84. // The slice must be sorted in ascending order.
  85. //
  86. func SearchFloat64s(a []float64, x float64) int {
  87. return Search(len(a), func(i int) bool { return a[i] >= x })
  88. }
  89. // SearchStrings searches for x in a sorted slice of strings and returns the index
  90. // as specified by Search. The return value is the index to insert x if x is not
  91. // present (it could be len(a)).
  92. // The slice must be sorted in ascending order.
  93. //
  94. func SearchStrings(a []string, x string) int {
  95. return Search(len(a), func(i int) bool { return a[i] >= x })
  96. }
  97. // Search returns the result of applying SearchInts to the receiver and x.
  98. func (p IntSlice) Search(x int) int { return SearchInts(p, x) }
  99. // Search returns the result of applying SearchFloat64s to the receiver and x.
  100. func (p Float64Slice) Search(x float64) int { return SearchFloat64s(p, x) }
  101. // Search returns the result of applying SearchStrings to the receiver and x.
  102. func (p StringSlice) Search(x string) int { return SearchStrings(p, x) }