Last active
December 7, 2017 02:49
-
-
Save jialinhuang00/104fbe50aa7172ad985767401acbc707 to your computer and use it in GitHub Desktop.
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
/*----------------------------------------------------------------------------- | |
the reference is from UdemyCourse: LearningAlgorithmsInJavascriptFromScratch | |
-----------------------------------------------------------------------------*/ | |
function binarySearch(numArr, key) { | |
numArr = numArr.sort((a, b) => a - b); | |
var midIndex = Math.floor(numArr.length / 2); | |
var midElement = numArr[midIndex]; | |
// if less than key, then after splicing, the array contains midElement | |
// remember splice() need to be assigned to a new variable | |
// splice(startIndex, HowMany) | |
if (midElement === key) return true; | |
// 留下後面,contain midElement | |
else if (midElement < key && numArr.length > 1) { | |
return binarySearch(numArr.splice(midIndex), key); | |
} | |
// 留下前面 | |
else if (midElement > key && numArr.length > 1) { | |
return binarySearch(numArr.splice(0, midIndex), key); | |
} | |
else return false; | |
} | |
binarySearch([5, 7, 12, 16, 36, 39, 42, 56, 71], 15); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment