stanevplamen

Binary search JS

Sep 27th, 2022
807
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. let recursiveFunction = function (arr, x, start, end) {
  2.      
  3.     // Base Condition
  4.     if (start > end) return false;
  5.  
  6.     // Find the middle index
  7.     let mid=Math.floor((start + end)/2);
  8.  
  9.     // Compare mid with given key x
  10.     if (arr[mid]===x) return true;
  11.          
  12.     // If element at mid is greater than x,
  13.     // search in the left half of mid
  14.     if(arr[mid] > x)
  15.         return recursiveFunction(arr, x, start, mid-1);
  16.     else
  17.  
  18.         // If element at mid is smaller than x,
  19.         // search in the right half of mid
  20.         return recursiveFunction(arr, x, mid+1, end);
  21. }
  22.  
  23. // Driver code
  24. let arr = [1, 3, 5, 7, 8, 9];
  25. let x = 5;
  26.  
  27. if (recursiveFunction(arr, x, 0, arr.length-1))
  28.     document.write("Element found!<br>");
  29. else document.write("Element not found!<br>");
  30.  
  31. x = 6;
  32.  
  33. if (recursiveFunction(arr, x, 0, arr.length-1))
  34.     document.write("Element found!<br>");
  35. else document.write("Element not found!<br>");
Advertisement
Add Comment
Please, Sign In to add comment