UNPKG

binary-search-jsv2

Version:
23 lines (21 loc) 530 B
export default function binarySearch(value, list) { let first = 0; let last = list.length - 1; let position = -1; let found = false; let middle; while (found === false && first <= last) { middle = Math.floor((first + last) / 2); if (list[middle] == value) { found = true; position = middle; } else if (list[middle] > value) { //if in lower half last = middle - 1; } else { //in in upper half first = middle + 1; } } return position; }