Created
October 14, 2019 12:26
-
-
Save Vinge1718/a5200f37f58a135106ecc5ebfb966e19 to your computer and use it in GitHub Desktop.
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
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