Source: Core/binarySearch.js

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