|
1 | 1 | /** |
2 | 2 | * Meta Binary Search (also known as One-Pass Binary Search) |
3 | 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. |
| 4 | + * Reference: https://www.geeksforgeeks.org/meta-binary-search-one-pass-binary-search/ |
9 | 5 | * |
| 6 | + * Works on sorted arrays by using bit manipulation to perform binary search in a single pass. |
10 | 7 | * Time Complexity: O(log N) |
11 | 8 | * Space Complexity: O(1) |
12 | 9 | * |
13 | | - * @param {number[]} arr - A sorted array to search within. |
| 10 | + * @param {number[]} arr - A sorted array. |
14 | 11 | * @param {number} target - The element to search for. |
15 | 12 | * @returns {number} - Index of the target if found, otherwise -1. |
16 | 13 | */ |
17 | | - |
18 | | -function metaBinarySearch(arr, target) { |
19 | | - let n = arr.length; |
| 14 | +function MetaBinarySearch(arr, target) { |
| 15 | + const n = arr.length; |
20 | 16 | if (n === 0) return -1; |
21 | 17 |
|
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 |
| 18 | + let pos = -1; |
| 19 | + for (let bit = Math.floor(Math.log2(n)); bit >= 0; bit--) { |
| 20 | + const newPos = pos + (1 << bit); |
28 | 21 | if (newPos < n && arr[newPos] <= target) { |
29 | | - pos = newPos; // move to that position |
| 22 | + pos = newPos; |
30 | 23 | } |
31 | | - bit >>= 1; // move to the next bit |
32 | 24 | } |
33 | 25 |
|
34 | 26 | return arr[pos] === target ? pos : -1; |
35 | 27 | } |
36 | 28 |
|
37 | | -export { metaBinarySearch }; |
| 29 | +export {MetaBinarySearch }; |
| 30 | + |
38 | 31 |
|
39 | 32 | // Example usage: |
40 | 33 | // console.log(metaBinarySearch([1, 3, 5, 7, 9, 11], 7)); // Output: 3 |
0 commit comments