From cc5b1e2e853ad6c7487eb1327e58349a242f0c37 Mon Sep 17 00:00:00 2001 From: Jenil Gajjar Date: Wed, 9 Oct 2024 20:21:11 +0530 Subject: [PATCH] dsa problem added using javascript for binary search (#338) --- JavaScript/binary_search.js | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 JavaScript/binary_search.js diff --git a/JavaScript/binary_search.js b/JavaScript/binary_search.js new file mode 100644 index 0000000..f8a6818 --- /dev/null +++ b/JavaScript/binary_search.js @@ -0,0 +1,28 @@ +function binarySearch(arr, key) { + let start = 0; + let end = arr.length - 1; + + while (start <= end) { + let mid = Math.floor(start + (end - start) / 2); + + if (arr[mid] === key) { + return mid; + } else if (arr[mid] > key) { + end = mid - 1; + } else { + start = mid + 1; + } + } + + return -1; +} + +const arr = [2, 3, 4, 10, 40]; +const key = 10; + +const result = binarySearch(arr, key); +if (result !== -1) { + console.log("Element found at index:", result); +} else { + console.log("Element not found"); +}