Facebook
From John, 3 Weeks ago, written in JavaScript.
Embed
Download Paste or View Raw
Hits: 120
  1. const binarySearch = (arr, x) => {
  2.  
  3.   // Initialise left and right bounds of search to start and end of arr
  4.   let left_index = 0;
  5.   let right_index = arr.length - 1;
  6.  
  7.   // While left_index and right_index have yet to overlap
  8.   while (left_index <= right_index) {
  9.    
  10.   // Find the midpoint between left_index and right_index
  11.     let mid_index = Math.floor((left_index + right_index) / 2);
  12.  
  13.     console.log("middle index", mid_index);
  14.    
  15.    // If the element at mid_index is x, return mid_index
  16.     // Use Math.floor to ensure that the index position is an integer not a decimal
  17.     if (arr[mid_index] === x) {
  18.       return mid_index;
  19.     }
  20.    
  21.     // Otherwise, if x is greater than elem at mid_index,
  22.     // update left_index to be 1 above mid_index
  23.     else if (arr[mid_index] < x) {
  24.       left_index = mid_index + 1;
  25.     }
  26.    
  27.  // Otherwise, if x is less than elem at mid_index,
  28.     // update right_index to be 1 below mid_index
  29.     else {
  30.       right_index = mid_index - 1;
  31.     }
  32.   }
  33.   // If x is not found, return -1
  34.   return -1;
  35. };
  36.  
  37. const myList = [2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
  38. const result = binarySearch(myList, 6); // 4
  39. console.log(result);