30 lines
833 B
JavaScript
30 lines
833 B
JavaScript
// https://www.freecodecamp.org/learn/coding-interview-prep/algorithms/implement-binary-search
|
|
|
|
function binarySearch(searchList, value) {
|
|
let arrayPath = [];
|
|
let first = 0;
|
|
let last = searchList.length - 1;
|
|
let middle;
|
|
while (true) {
|
|
middle = Math.floor((last - first) / 2) + first;
|
|
if (searchList[middle] === arrayPath[arrayPath.length - 1]) {
|
|
return "Value Not Found";
|
|
}
|
|
arrayPath.push(searchList[middle]);
|
|
if (searchList[middle] === value) {
|
|
return arrayPath;
|
|
} else if (searchList[middle] > value) {
|
|
last = middle - 1;
|
|
} else if (searchList[middle] < value) {
|
|
first = middle + 1;
|
|
}
|
|
}
|
|
}
|
|
|
|
const testArray = [
|
|
0, 1, 2, 3, 4, 5, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22,
|
|
23, 49, 70,
|
|
];
|
|
|
|
console.log(binarySearch(testArray, 0)); //[13, 5, 2, 0]
|