From 8dd19ce8d4f3511d248e6c65d3d93df448ee2080 Mon Sep 17 00:00:00 2001 From: Manish Date: Tue, 22 Aug 2023 10:54:05 +1000 Subject: [PATCH] Algorithms: Implement Binary Search --- Algorithms/binarySearch.js | 29 +++++++++++++++++++++++++++++ 1 file changed, 29 insertions(+) create mode 100644 Algorithms/binarySearch.js diff --git a/Algorithms/binarySearch.js b/Algorithms/binarySearch.js new file mode 100644 index 0000000..f04885a --- /dev/null +++ b/Algorithms/binarySearch.js @@ -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]