Skip to content

Commit

Permalink
dsa problem added using javascript for binary search (#338)
Browse files Browse the repository at this point in the history
  • Loading branch information
JenilGajjar20 authored Oct 9, 2024
1 parent 0958e89 commit cc5b1e2
Showing 1 changed file with 28 additions and 0 deletions.
28 changes: 28 additions & 0 deletions JavaScript/binary_search.js
Original file line number Diff line number Diff line change
@@ -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");
}

0 comments on commit cc5b1e2

Please sign in to comment.