-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinarySearch.js
More file actions
40 lines (34 loc) · 1.01 KB
/
BinarySearch.js
File metadata and controls
40 lines (34 loc) · 1.01 KB
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
38
39
40
/**
* Binary Search
*
* Time Complexity: O(log n) where n = |items|
* We assume that items is sorted from greatest to smallest.
* @param {int} n
*/
function binarySearch(items, find) {
let l = 0;
let r = items.length - 1;
while (l <= r) {
const m = Math.floor((l + r) / 2);
if (items[m] < find) {
l = m + 1;
} else if (items[m] > find) {
r = m - 1;
} else {
return m; // element is present
}
}
return false; // element is not present
}
// ----------------
// --- Examples ---
// ----------------
let items = [5, 13, 22, 64, 157, 289, 333, 987, 1010];
let find = 1;
console.log('binarySearch([%s], %d) = %s', items.join(', '), find, binarySearch(items, find));
items = [5, 13, 22, 64, 157, 289, 333, 987, 1010];
find = 157;
console.log('binarySearch([%s], %d) = %s', items.join(', '), find, binarySearch(items, find));
items = [5, 13, 22, 64, 157, 289, 333, 987, 1010];
find = 5;
console.log('binarySearch([%s], %d) = %s', items.join(', '), find, binarySearch(items, find));