Created
February 13, 2022 16:58
-
-
Save xihai01/045cd00527f0ef7feebceca537d53f28 to your computer and use it in GitHub Desktop.
BInary Search Implementation in JS
This file contains 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
const binarySearch = function (array, target) { | |
// initialise variables to point to bounds of array | |
let bottom = 0; | |
let top = array.length - 1; | |
let middle; | |
while (bottom <= top) { | |
// get index of middle value | |
middle = Math.floor((bottom + top) / 2); | |
const middleValue = array[middle]; | |
// return middle index if found | |
if (middleValue === target) { | |
return middle; | |
} | |
if (middleValue < target) { | |
bottom = middle + 1; | |
} | |
if (middleValue > target) { | |
top = middle - 1; | |
} | |
} | |
// return null if target not in array | |
return null; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment