Skip to content

Commit a0f3949

Browse files
Added Meta Binary Search algorithm
1 parent 08d8c6b commit a0f3949

File tree

1 file changed

+40
-0
lines changed

1 file changed

+40
-0
lines changed

Search/MetaBinarySearch.js

Lines changed: 40 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
/**
2+
* Meta Binary Search (also known as One-Pass Binary Search)
3+
*
4+
* This algorithm uses bit manipulation to perform a binary search
5+
* in a single pass without using recursion or a traditional loop-based binary search.
6+
*
7+
* It works on sorted arrays by progressively checking bits of the index
8+
* and narrowing down the possible position of the target element.
9+
*
10+
* Time Complexity: O(log N)
11+
* Space Complexity: O(1)
12+
*
13+
* @param {number[]} arr - A sorted array to search within.
14+
* @param {number} target - The element to search for.
15+
* @returns {number} - Index of the target if found, otherwise -1.
16+
*/
17+
18+
function metaBinarySearch(arr, target) {
19+
let n = arr.length;
20+
if (n === 0) return -1;
21+
22+
// Get the highest power of 2 less than or equal to n
23+
let pos = 0;
24+
let bit = 1 << Math.floor(Math.log2(n));
25+
26+
while (bit > 0) {
27+
let newPos = pos | bit; // test the bit
28+
if (newPos < n && arr[newPos] <= target) {
29+
pos = newPos; // move to that position
30+
}
31+
bit >>= 1; // move to the next bit
32+
}
33+
34+
return arr[pos] === target ? pos : -1;
35+
}
36+
37+
export { metaBinarySearch };
38+
39+
// Example usage:
40+
// console.log(metaBinarySearch([1, 3, 5, 7, 9, 11], 7)); // Output: 3

0 commit comments

Comments
 (0)