Skip to content

Instantly share code, notes, and snippets.

@bran921007
Created March 30, 2022 16:26
Show Gist options
  • Save bran921007/33a6a6aed36480a5f7f77f0e88964b30 to your computer and use it in GitHub Desktop.
Save bran921007/33a6a6aed36480a5f7f77f0e88964b30 to your computer and use it in GitHub Desktop.
Binary Search
let arr = [-2, 3, 4, 7, 8, 9, 11, 13];
let arr2 = [13, -2, 3, 4, 7, 8, 9, 11];
let arr3 = [8, 9, 11, 13, -2, 3, 4, 7];
function binarySearch(arr, target){
left = 0;
right = arr.length - 1;
while(left <= right){
mid = Math.floor((left + right)/ 2);
if(arr[mid] == target){
return mid;
}else if(arr[mid] < target){
left = mid + 1;
}else if(arr[mid] > target){
right = mid - 1;
}
}
return -1;
}
binarySearch(arr3, 11)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment