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