akhayoon

Binary Search

Sep 25th, 2021 (edited)
150
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let iterativeFunction = function (arr, x) {
  2.  
  3.     let start=0, end=arr.length-1;
  4.          
  5.     // Iterate while start not meets end
  6.     while (start<=end){
  7.  
  8.         // Find the mid index
  9.         let mid=Math.floor((start + end)/2);
  10.  
  11.         // If element is present at mid, return True
  12.         if (arr[mid]===x) return true;
  13.  
  14.         // Else look in left or right half accordingly
  15.         else if (arr[mid] < x)
  16.              start = mid + 1;
  17.         else
  18.              end = mid - 1;
  19.     }
  20.  
  21.  
Add Comment
Please, Sign In to add comment