Skip to content
This repository was archived by the owner on Jun 26, 2022. It is now read-only.

Commit 23c00ea

Browse files
Merge pull request #50 from rasacharjee/binarySearch_Javascript
Binary search in javascript added
2 parents cd0b78c + 2d9bf34 commit 23c00ea

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed

js/rasacharjee_binarySearch.js

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
// Iterative function to implement Binary Search
2+
let iterativeFunction = function (arr, x) {
3+
let start = 0,
4+
end = arr.length - 1;
5+
6+
// Iterate while start not meets end
7+
while (start <= end) {
8+
// Find the mid index
9+
let mid = Math.floor((start + end) / 2);
10+
11+
// If element is present at mid, return True
12+
if (arr[mid] === x) return true;
13+
// Else look in left or right half accordingly
14+
else if (arr[mid] < x) start = mid + 1;
15+
else end = mid - 1;
16+
}
17+
18+
return false;
19+
};
20+
21+
// Driver code
22+
let arr = [1, 3, 5, 7, 8, 9];
23+
let x = 5;
24+
25+
if (iterativeFunction(arr, x, 0, arr.length - 1)) console.log("Element found!");
26+
else console.log("Element not found!");
27+
28+
x = 10;
29+
30+
if (iterativeFunction(arr, x, 0, arr.length - 1)) console.log("Element found!");
31+
else console.log("Element not found!");

0 commit comments

Comments
 (0)