Advertisement
aleffelixf

Binary Search in Node.js

Sep 10th, 2021 (edited)
1,016
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict'
  2.  
  3. const binarySearch = (arr, value) => {
  4.     let begin = 0;
  5.     let end = arr.length - 1;
  6.     let middle = parseInt(end / 2);
  7.  
  8.     let index = -1;
  9.  
  10.     while (begin <= end) {
  11.         if (arr[middle] === value) {
  12.             index = middle;
  13.             break;
  14.         } else {
  15.             if (arr[middle] > value) {
  16.                 end = middle - 1;
  17.             } else {
  18.                 begin = middle + 1;
  19.             }
  20.             middle = parseInt((begin + end) / 2);
  21.         }
  22.     }
  23.  
  24.     return index;
  25. }
  26.  
  27. console.log('Looking for 6: ', binarySearch([1, 4, 6, 12, 15, 23, 34, 70], 6));
  28. console.log('Looking for 34: ', binarySearch([1, 4, 6, 12, 15, 23, 34, 70], 34));
  29. console.log('Looking for 1: ', binarySearch([1, 4, 6, 12, 15, 23, 34, 70], 1));
  30. console.log('Looking for 30: ', binarySearch([1, 4, 6, 12, 15, 23, 34, 70], 30));
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement