Binary Search

  1. 'use strict';
  2. /* Binary search number algorithm */
  3. let i = 0;
  4. const binarySearch = ({ array, head = 0, number, tail }) => {
  5. if (i > 10) return 'stack overflow'; i += 1;
  6. tail = tail || array.length;
  7. const remainingArray = array.slice(head, tail);
  8. const index = Math.floor(remainingArray.length / 2);
  9. const normalizedIndex = head + index;
  10. if (remainingArray[index] === number) {
  11. console.log('found in index ', normalizedIndex);
  12. return normalizedIndex;
  13. }
  14. if (number < remainingArray[index]) {
  15. tail = normalizedIndex;
  16. } else {
  17. head = normalizedIndex;
  18. }
  19. console.log('head', head, 'tail', tail, remainingArray, 'index', normalizedIndex);
  20. return binarySearch({ array, head, number, tail });
  21. };
  1. // Tests
  2. let array;
  3. array = [0,10,20,30,40,50,60,70,80,90,100,110,120,130,140,150];
  4. console.log(binarySearch({ array, number: 20 }) );
  5. i = 0;
  6. console.log(binarySearch({ array, number: 70 }) );
  7. i = 0;
  8. console.log(binarySearch({ array, number: 130 }) );
  9. i = 0;
  10. console.log(binarySearch({ array, number: 0 }) );
  11. i = 0;
  12. array = [0,1,2,3,4,5];
  13. console.log(binarySearch({ array, number: 5 }) );
  14. array = [0,1,2,3,4,5,6];
  15. console.log(binarySearch({ array, number: 4 }) );