From 6c8e1697eab443f3570262b2929b4ede6a906b41 Mon Sep 17 00:00:00 2001 From: Satyam Singh <56315878+satcasm@users.noreply.github.com> Date: Wed, 27 Jan 2021 19:39:36 +0530 Subject: [PATCH] add binary search in js (#31) --- searching/README.md | 1 + searching/js/binary-search.js | 24 ++++++++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 searching/js/binary-search.js diff --git a/searching/README.md b/searching/README.md index 786633bd..269013d0 100644 --- a/searching/README.md +++ b/searching/README.md @@ -15,6 +15,7 @@ ### JavaScript 1. [Linear Search](js/linear-search.js) +2. [Binary Search](js/binary-search.js) ### Java diff --git a/searching/js/binary-search.js b/searching/js/binary-search.js new file mode 100644 index 00000000..2cfc4b22 --- /dev/null +++ b/searching/js/binary-search.js @@ -0,0 +1,24 @@ +function binarySearch(value, list) { + let first = 0; //left endpoint + let last = list.length - 1; //right endpoint + let position = -1; // After looping if the search item is not found, we will return -1 + let found = false; // When item is found we set its value to true + let middle; + + while (found === false && first <= last) { + middle = Math.floor((first + last)/2); + if (list[middle] == value) { // If the element is present at the middle itself + 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; +} + +console.log(binarySearch(6,[2, 6, 8])); //expected output = 1 +console.log(binarySearch(10,[2, 3, 10, 14])); //expected output = 2 +console.log(binarySearch(1,[2, 6, 8])); //expected output = -1 \ No newline at end of file