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. left = mid+1;
  9. } else if(arr[mid] > target) {
  10. right = mid-1;
  11. } else {
  12. return mid;
  13. }
  14. }
  15. return -1;
  16. }
  17.  
  18. console.log(binarySearch([1, 5, 6, 9, 13], 5, 11))
Success #stdin #stdout 0.02s 5712KB
stdin
Standard input is empty
stdout
-1