Skip to content

Instantly share code, notes, and snippets.

@jialinhuang00
Last active December 7, 2017 02:49
Show Gist options
  • Save jialinhuang00/104fbe50aa7172ad985767401acbc707 to your computer and use it in GitHub Desktop.
Save jialinhuang00/104fbe50aa7172ad985767401acbc707 to your computer and use it in GitHub Desktop.
/*-----------------------------------------------------------------------------
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