Skip to content

Commit 37d39e0

Browse files
committed
Added binary search algo
1 parent 1cbf568 commit 37d39e0

File tree

1 file changed

+24
-0
lines changed

1 file changed

+24
-0
lines changed

base-algorithms/binarySearch.ts

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,24 @@
1+
/**
2+
* Binary search algorithm
3+
* Complexity: O(log(n))
4+
*/
5+
6+
function binarySearch(arr: number[], item: number) {
7+
let start = 0;
8+
let end = arr.length - 1;
9+
10+
while (start <= end) {
11+
let mid = Math.floor(start + end) / 2;
12+
let guess = arr[mid];
13+
14+
if (guess === item) {
15+
return true;
16+
} else if (guess < item) {
17+
start = mid + 1;
18+
} else {
19+
end = mid - 1;
20+
}
21+
}
22+
23+
return false;
24+
}

0 commit comments

Comments
 (0)