-
Notifications
You must be signed in to change notification settings - Fork 19
/
Copy pathbinary-search.js
37 lines (27 loc) · 916 Bytes
/
binary-search.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
// Iterative function to implement Binary Search
let iterativeFunction = function (arr, x) {
let start=0, end=arr.length-1;
// Iterate while start not meets end
while (start<=end){
// Find the mid index
let mid=Math.floor((start + end)/2);
// If element is present at mid, return True
if (arr[mid]===x) return true;
// Else look in left or right half accordingly
else if (arr[mid] < x)
start = mid + 1;
else
end = mid - 1;
}
return false;
}
// Driver code
let arr = [1, 3, 5, 7, 8, 9];
let x = 5;
if (iterativeFunction(arr, x, 0, arr.length-1))
document.write("Element found!<br>");
else document.write("Element not found!<br>");
x = 6;
if (iterativeFunction(arr, x, 0, arr.length-1))
document.write("Element found!<br>");
else document.write("Element not found!<br>");