bsearch.h 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /*
  2. ** Command & Conquer Renegade(tm)
  3. ** Copyright 2025 Electronic Arts Inc.
  4. **
  5. ** This program is free software: you can redistribute it and/or modify
  6. ** it under the terms of the GNU General Public License as published by
  7. ** the Free Software Foundation, either version 3 of the License, or
  8. ** (at your option) any later version.
  9. **
  10. ** This program is distributed in the hope that it will be useful,
  11. ** but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. ** GNU General Public License for more details.
  14. **
  15. ** You should have received a copy of the GNU General Public License
  16. ** along with this program. If not, see <http://www.gnu.org/licenses/>.
  17. */
  18. #if _MSC_VER >= 1000
  19. #pragma once
  20. #endif // _MSC_VER >= 1000
  21. #ifndef BSEARCH_H
  22. #define BSEARCH_H
  23. /*
  24. ** Binary searching template. It can be faster than the built in C library
  25. ** version since the comparison function can be inlined. If the comparison
  26. ** process is significantly more time consuming than the overhead of
  27. ** a function call, then using the C library version would be appropriate.
  28. */
  29. template<class T>
  30. T * Binary_Search(T * A, int n, T const & target)
  31. {
  32. const T * pointer = A;
  33. int stride = n;
  34. /*
  35. ** Keep binary searching until a match has been found
  36. ** or the search has resulted in no match.
  37. */
  38. while (0 < stride) {
  39. int const pivot = stride / 2;
  40. T const * const tryptr = pointer + pivot;
  41. /*
  42. ** Binary stride forward or backward depending on if the candidate
  43. ** element is smaller or larger than the target element. If
  44. ** smaller, then merely adjusting the stride is required. If larger,
  45. ** then the base pointer must be adjusted and the stride must be
  46. ** moved backward.
  47. */
  48. if (target < *tryptr) {
  49. stride = pivot;
  50. } else {
  51. /*
  52. ** An exact match results in the pointer being found
  53. ** and returned to the caller. This check is performed
  54. ** here since 50% of the time, the first compare will
  55. ** be true and thus the equality comparison would be
  56. ** called less often -- should be faster as a result.
  57. */
  58. if (*tryptr == target) {
  59. return ((T *) tryptr);
  60. }
  61. pointer = tryptr + 1;
  62. stride -= pivot + 1;
  63. }
  64. }
  65. return (NULL);
  66. }
  67. #endif