Skip to content

Instantly share code, notes, and snippets.

@Vinge1718
Created October 14, 2019 12:26
Show Gist options
  • Save Vinge1718/a5200f37f58a135106ecc5ebfb966e19 to your computer and use it in GitHub Desktop.
Save Vinge1718/a5200f37f58a135106ecc5ebfb966e19 to your computer and use it in GitHub Desktop.
function binarySearch(numberArray, key){
var firstIndex = 0;
var lastIndex = numberArray.length - 1;
while (firstIndex <= lastIndex){
// Find the mid index
var middleIndex = Math.floor((firstIndex + lastIndex) / 2);
var middleElement = numberArray[middleIndex];
// If element is present at mid, return True
if (middleElement === key) return true;
else if (middleElement < key)
firstIndex = middleIndex + 1;
else
lastIndex = middleIndex - 1;
}
return false;
}
//TEST
binarySearch([5, 7, 12, 16, 36, 39, 42, 56, 71], 97);
// Exercises
// Instead of returning true - return the location of the key if found
//Assignment
//Try to implement Linear search
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment