From 7813d5ec6213f8c4fdc5bff9e3392fca5fcc71d6 Mon Sep 17 00:00:00 2001 From: akashsolanki1101 <52728998+akashsolanki1101@users.noreply.github.com> Date: Thu, 31 Oct 2019 20:23:22 +0530 Subject: [PATCH] Adding Binary Search --- .../search/binary-search/BinarySearch.js | 27 +++++++++++++++++++ 1 file changed, 27 insertions(+) create mode 100644 src/algorithms/search/binary-search/BinarySearch.js diff --git a/src/algorithms/search/binary-search/BinarySearch.js b/src/algorithms/search/binary-search/BinarySearch.js new file mode 100644 index 00000000..d39b0143 --- /dev/null +++ b/src/algorithms/search/binary-search/BinarySearch.js @@ -0,0 +1,27 @@ +var myList = [1, 3, 5, 7, 9]; + +function binarySearch(myList, itemToFind) { + var low = 0, + high = myList.length - 1, + mid, + guessed; + + while(low <= high) { + mid = Math.floor((low + high) / 2), + guessed = myList[mid]; + + if(guessed === itemToFind) { + console.log('Found item at index: ' + mid + ', value is ' + guessed); + return; + } + if(itemToFind < guessed) { + high = mid - 1; + } else { + low = mid + 1; + } + } + + return null; +} + +binarySearch(myList, 3);