1. function binarySearch(array, value) {
  2. let low = 0,
  3. high = array.length - 1;
  4. while (low <= high) {
  5. let mid = (low + high) / 2;
  6. if (value === array[mid]) {
  7. return mid;
  8. } else if (value < array[mid]) {
  9. high = mid - 1;
  10. } else if (value > array[mid]) {
  11. low = mid + 1;
  12. }
  13. }
  14. console.log('值不存在');
  15. return undefined;
  16. }

重写

查找前需要排序

  1. function binarySearch(arr,value){
  2. if(arr.length === 0) return null
  3. let bottom = 0,
  4. top = arr.length - 1
  5. while(bottom<=top){
  6. let index = Math.floor((bottom+top)/2)
  7. if(arr[index] === value){
  8. return index
  9. }else if(arr[index]>value){
  10. top = index - 1
  11. }else if(arr[index]<value){
  12. bottom = index + 1
  13. }
  14. }
  15. return null
  16. }