-
Notifications
You must be signed in to change notification settings - Fork 8
/
binarySearch.ts
73 lines (68 loc) · 2.18 KB
/
binarySearch.ts
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
function binSearchIterative(arr, target) {
// assuming sorted array of numbers
let left = 0;
let right = arr.length - 1;
while (left <= right) {
let mid = Math.floor(left + right / 2);
if (arr[mid] === target) return mid;
if (left === right) {
return false;
}
if (arr[mid] > target) {
right = mid - 1;
continue;
}
if (arr[mid] < target) {
left = mid + 1;
continue;
}
}
return false;
}
function binarySearchRec(arr, target, i = 0, j = arr.length - 1) {
// assuming arr is sorted
if (j < i) return false;
const mid = Math.floor((i + j) / 2);
if (arr[mid] === target) return mid;
if (target < mid) {
return binarySearchRec(arr, target, i, mid - 1);
} else {
return binarySearchRec(arr, target, mid + 1, j);
}
}
console.log(binarySearchRec([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)); // 3
console.log(binarySearchRec([0, 1, 2, 4, 5, 6, 7, 8, 9], 3)); // false
console.log(binarySearchRec([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 30)); // false
console.log(binarySearchRec([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 0)); // 0
console.log(binarySearchRec([0, 1, 2, 3, 4, 5, 6, 7, 8], 1)); // 1
console.log(binarySearchRec([0, 1], 1)); // 1
console.log(binarySearchRec([0, 1], 0)); // 0
console.log(binarySearchRec([0], 0)); // 0
console.log(binarySearchRec([0], 1)); // false
console.log(binarySearchRec([], 1)); // false
// not tested yet
console.log(binIter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 3)); // 3
console.log(binIter([0, 1, 2, 4, 5, 6, 7, 8, 9], 3)); // false
console.log(binIter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 30)); // false
console.log(binIter([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 0)); // 0
console.log(binIter([0, 1, 2, 3, 4, 5, 6, 7, 8], 1)); // 1
console.log(binIter([0, 1], 1)); // 1
console.log(binIter([0, 1], 0)); // 0
console.log(binIter([0], 0)); // 0
console.log(binIter([0], 1)); // false
console.log(binIter([], 1)); // false
function binIter(arr, target) {
let low = 0;
let high = arr.length - 1;
while (low <= high) {
let mid = low + Math.floor((high - low) / 2);
let cand = arr[mid];
if (cand === target) return mid;
if (target > cand) {
low = mid + 1;
} else {
high = mid - 1;
}
}
return false;
}