-
Notifications
You must be signed in to change notification settings - Fork 107
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
dsa problem added using javascript for binary search (#338)
- Loading branch information
1 parent
0958e89
commit cc5b1e2
Showing
1 changed file
with
28 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | ||
} |