Skip to content

Instantly share code, notes, and snippets.

@dondevi
Last active February 8, 2018 09:33
Show Gist options
  • Save dondevi/9de1c09c2ba5a615bcf68a04e86403fa to your computer and use it in GitHub Desktop.
Save dondevi/9de1c09c2ba5a615bcf68a04e86403fa to your computer and use it in GitHub Desktop.
/**
* 二分查找
* @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