@brief find index of a sorted array such that arr[i] <= key < arr[i + 1]. * * If an starting index guess is in-range, the array values around this * index are first checked. This allows for repeated calls for well-ordered * keys (a very common case) to use the previous index as a very good guess. * * If the guess value is not useful, bisection of the array is used to * find the index. If
| 412 | * @return index |
| 413 | */ |
| 414 | static npy_intp |
| 415 | binary_search_with_guess(const npy_double key, const npy_double *arr, |
| 416 | npy_intp len, npy_intp guess) |
| 417 | { |
| 418 | npy_intp imin = 0; |
| 419 | npy_intp imax = len; |
| 420 | |
| 421 | /* Handle keys outside of the arr range first */ |
| 422 | if (key > arr[len - 1]) { |
| 423 | return len; |
| 424 | } |
| 425 | else if (key < arr[0]) { |
| 426 | return -1; |
| 427 | } |
| 428 | |
| 429 | /* |
| 430 | * If len <= 4 use linear search. |
| 431 | * From above we know key >= arr[0] when we start. |
| 432 | */ |
| 433 | if (len <= 4) { |
| 434 | return _linear_search(key, arr, len, 1); |
| 435 | } |
| 436 | |
| 437 | if (guess > len - 3) { |
| 438 | guess = len - 3; |
| 439 | } |
| 440 | if (guess < 1) { |
| 441 | guess = 1; |
| 442 | } |
| 443 | |
| 444 | /* check most likely values: guess - 1, guess, guess + 1 */ |
| 445 | if (key < arr[guess]) { |
| 446 | if (key < arr[guess - 1]) { |
| 447 | imax = guess - 1; |
| 448 | /* last attempt to restrict search to items in cache */ |
| 449 | if (guess > LIKELY_IN_CACHE_SIZE && |
| 450 | key >= arr[guess - LIKELY_IN_CACHE_SIZE]) { |
| 451 | imin = guess - LIKELY_IN_CACHE_SIZE; |
| 452 | } |
| 453 | } |
| 454 | else { |
| 455 | /* key >= arr[guess - 1] */ |
| 456 | return guess - 1; |
| 457 | } |
| 458 | } |
| 459 | else { |
| 460 | /* key >= arr[guess] */ |
| 461 | if (key < arr[guess + 1]) { |
| 462 | return guess; |
| 463 | } |
| 464 | else { |
| 465 | /* key >= arr[guess + 1] */ |
| 466 | if (key < arr[guess + 2]) { |
| 467 | return guess + 1; |
| 468 | } |
| 469 | else { |
| 470 | /* key >= arr[guess + 2] */ |
| 471 | imin = guess + 2; |
no test coverage detected