Created
March 30, 2022 16:26
-
-
Save bran921007/33a6a6aed36480a5f7f77f0e88964b30 to your computer and use it in GitHub Desktop.
Binary Search
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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