forked from super30admin/PreCourse-2
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExercise_1.js
More file actions
36 lines (33 loc) · 836 Bytes
/
Exercise_1.js
File metadata and controls
36 lines (33 loc) · 836 Bytes
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
// Time Complexity: O(log n)
// Space Complexity: O(1)
class BinarySearch {
// Returns index of x if it is present in arr[l.. r], else return -1
binarySearch(arr, left, right, target) {
if (!arr || arr.length === 0) return -1;
if (left === right) {
return arr[left] === target ? left : -1;
}
while (left <= right) {
let mid = Math.floor((left + right) / 2);
if (arr[mid] === target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
}
// Driver method to test above
const ob = new BinarySearch();
const arr = [2, 3, 4, 10, 40];
const n = arr.length;
const x = 10;
const result = ob.binarySearch(arr, 0, n - 1, x);
if (result === -1) {
console.log("Element not present");
} else {
console.log("Element found at index " + result);
}