Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 825b8f5

Browse files
implemented Binary search algorithm
1 parent 792a0ce commit 825b8f5

File tree

2 files changed

+21
-0
lines changed

2 files changed

+21
-0
lines changed

‎README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,4 +28,5 @@
2828
| Problem - 24 | Find your crushes phone number |
2929
| Problem - 25 | Plus One - 66.LeetCode - Easy |
3030
| Problem - 26 | Linear Search implementation with JS |
31+
| Problem - 27 | Binary Search implementation with JS |
3132
<!-- | Problem - 22 | | -->

‎problem-27.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
// binary search implementation
2+
const arr = [1, 3, 5, 7, 8, 9];
3+
4+
const binarySearch = (arr, x, start = 0, end = arr.length) => {
5+
// If the item does not exist, return -1
6+
if (end < start) return -1;
7+
8+
// Calculate middle index of the array
9+
let mid = Math.floor((start + end) / 2);
10+
11+
// Is the middle a match?
12+
if (arr[mid] === x) return mid;
13+
14+
// Is the middle less than x
15+
if (arr[mid] < x) return binarySearch(arr, x, mid + 1, end);
16+
// Else the middle is more than x
17+
else return binarySearch(arr, x, start, mid - 1);
18+
};
19+
20+
console.log(binarySearch(arr, 9));

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /