-
-
Notifications
You must be signed in to change notification settings - Fork 5.8k
Expand file tree
/
Copy pathMetaBinarySearch.js
More file actions
32 lines (28 loc) · 921 Bytes
/
MetaBinarySearch.js
File metadata and controls
32 lines (28 loc) · 921 Bytes
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
/**
* Meta Binary Search (also known as One-Pass Binary Search)
*
* Reference: https://www.geeksforgeeks.org/meta-binary-search-one-pass-binary-search/
*
* Works on sorted arrays by using bit manipulation to perform binary search in a single pass.
* Time Complexity: O(log N)
* Space Complexity: O(1)
*
* @param {number[]} arr - A sorted array.
* @param {number} target - The element to search for.
* @returns {number} - Index of the target if found, otherwise -1.
*/
function MetaBinarySearch(arr, target) {
const n = arr.length
if (n === 0) return -1
let pos = -1
for (let bit = Math.floor(Math.log2(n)); bit >= 0; bit--) {
const newPos = pos + (1 << bit)
if (newPos < n && arr[newPos] <= target) {
pos = newPos
}
}
return arr[pos] === target ? pos : -1
}
export { MetaBinarySearch }
// Example usage:
// console.log(metaBinarySearch([1, 3, 5, 7, 9, 11], 7)); // Output: 3