Algorithms: Implement Binary Search
This commit is contained in:
parent
33c0806441
commit
8dd19ce8d4
29
Algorithms/binarySearch.js
Normal file
29
Algorithms/binarySearch.js
Normal file
@ -0,0 +1,29 @@
|
||||
// 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]
|
Loading…
Reference in New Issue
Block a user