fork download
  1. // your code goes here
  2.  
  3. function binarySearch(arr, n, target) {
  4. let left=0, right = n-1, mid;
  5. while(left<=right) {
  6. mid = Math.floor((left+right)/2);
  7. if(arr[mid] > target) {
  8. right = mid-1;
  9. } else if(arr[mid] < target) {
  10. left = mid+1;
  11. } else {
  12. return mid;
  13. }
  14. }
  15. return -1;
  16. }
  17.  
  18. console.log(binarySearch([2, 4, 5, 7, 8, 9, 11], 7, 3))
Success #stdin #stdout 0.05s 16804KB
stdin
Standard input is empty
stdout
-1