Skip to content

Commit 8a81e61

Browse files
authored
Merge pull request deutranium#243 from masoudnemati/master
Implement JavaScript BinarySearch
2 parents 7f260ad + 326089e commit 8a81e61

File tree

1 file changed

+30
-0
lines changed

1 file changed

+30
-0
lines changed
Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
function binarySearch(arr, x) {
2+
let left = 0;
3+
let right = arr.length - 1;
4+
5+
while (left <= right) {
6+
let mid = Math.round((left + right) / 2); // calculate the mid index
7+
8+
// if value is same as value on midIndex, simply return midIndex
9+
if (arr[mid] == x) {
10+
return mid;
11+
}
12+
13+
// when value is less than middle value, we search in the left half
14+
if (arr[mid] < x) {
15+
left = mid + 1;
16+
17+
// when value is greater than middle value, we search in the right half
18+
} else {
19+
right = mid - 1;
20+
}
21+
}
22+
return -1;
23+
}
24+
25+
// testCase
26+
// sorted array to search the value in
27+
const arr = [2, 12, 23, 34, 45, 52, 61, 75, 85, 99];
28+
const x = 85;
29+
30+
console.log(binarySearch(arr, x));

0 commit comments

Comments
 (0)