binarySearch.js 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. import Check from "./Check.js";
  2. /**
  3. * Finds an item in a sorted array.
  4. *
  5. * @function
  6. * @param {Array} array The sorted array to search.
  7. * @param {*} itemToFind The item to find in the array.
  8. * @param {binarySearchComparator} comparator The function to use to compare the item to
  9. * elements in the array.
  10. * @returns {number} The index of <code>itemToFind</code> in the array, if it exists. If <code>itemToFind</code>
  11. * does not exist, the return value is a negative number which is the bitwise complement (~)
  12. * of the index before which the itemToFind should be inserted in order to maintain the
  13. * sorted order of the array.
  14. *
  15. * @example
  16. * // Create a comparator function to search through an array of numbers.
  17. * function comparator(a, b) {
  18. * return a - b;
  19. * };
  20. * const numbers = [0, 2, 4, 6, 8];
  21. * const index = Cesium.binarySearch(numbers, 6, comparator); // 3
  22. */
  23. function binarySearch(array, itemToFind, comparator) {
  24. //>>includeStart('debug', pragmas.debug);
  25. Check.defined("array", array);
  26. Check.defined("itemToFind", itemToFind);
  27. Check.defined("comparator", comparator);
  28. //>>includeEnd('debug');
  29. let low = 0;
  30. let high = array.length - 1;
  31. let i;
  32. let comparison;
  33. while (low <= high) {
  34. i = ~~((low + high) / 2);
  35. comparison = comparator(array[i], itemToFind);
  36. if (comparison < 0) {
  37. low = i + 1;
  38. continue;
  39. }
  40. if (comparison > 0) {
  41. high = i - 1;
  42. continue;
  43. }
  44. return i;
  45. }
  46. return ~(high + 1);
  47. }
  48. /**
  49. * A function used to compare two items while performing a binary search.
  50. * @callback binarySearchComparator
  51. *
  52. * @param {*} a An item in the array.
  53. * @param {*} b The item being searched for.
  54. * @returns {number} Returns a negative value if <code>a</code> is less than <code>b</code>,
  55. * a positive value if <code>a</code> is greater than <code>b</code>, or
  56. * 0 if <code>a</code> is equal to <code>b</code>.
  57. *
  58. * @example
  59. * function compareNumbers(a, b) {
  60. * return a - b;
  61. * }
  62. */
  63. export default binarySearch;