Last active
February 8, 2018 09:33
-
-
Save dondevi/9de1c09c2ba5a615bcf68a04e86403fa 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
/** | |
* 二分查找 | |
* @param {Array} array - 有序数组 | |
* @param {Number} value - 查找目标值 | |
*/ | |
function binarySearch (array, value) { | |
let index = 0; | |
let left = 0; | |
let right = array.length - 1; | |
while (left < right) { | |
index = Math.floor(left + (right - left) / 2); | |
if (value > array[index]) { | |
left = index + 1; | |
} else { | |
right = index; | |
} | |
}; | |
if (value === array[right]) { | |
return right; | |
} | |
return -1; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment