binarySearch that finds exact matching entry. Returns non-zero index when found, or -1 when not found Inspired by sort.Search but makes uses of tri-state comparator to eliminate the last comparison when we want to find exact match, not insertion point.
(n int, compare func(int) (int, error))
| 282 | // Inspired by sort.Search but makes uses of tri-state comparator to eliminate the last comparison when |
| 283 | // we want to find exact match, not insertion point. |
| 284 | func binarySearch(n int, compare func(int) (int, error)) (int, error) { |
| 285 | i, j := 0, n |
| 286 | for i < j { |
| 287 | h := int(uint(i+j) >> 1) // avoid overflow when computing h |
| 288 | c, err := compare(h) |
| 289 | if err != nil { |
| 290 | return -1, err |
| 291 | } |
| 292 | // i ≤ h < j |
| 293 | switch c { |
| 294 | case 0: |
| 295 | // Found exact match |
| 296 | return h, nil |
| 297 | case -1: |
| 298 | j = h |
| 299 | case 1: |
| 300 | i = h + 1 |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | // No match |
| 305 | return -1, nil |
| 306 | } |