fork download
  1. // GOOD ✅ O (log n)
  2. function binarySearch(arr, value, left, right) {
  3. while (left <= right) {
  4. let mid = Math.floor((left + right) / 2);
  5. if (arr[mid] === value) return mid;
  6. if (arr[mid] < value) left = mid + 1;
  7. else right = mid - 1;
  8. }
  9. return -1;
  10. }
  11. const sortedArray = [1, 3, 5, 7, 9, 11, 13];
  12. console.log(binarySearch(sortedArray, 7, 0, sortedArray.length - 1)); // Output: 3
  13.  
Success #stdin #stdout 0.05s 18196KB
stdin
Standard input is empty
stdout
3