Skip to content

Commit a84306c

Browse files
Fixed code style issues for Meta Binary Search
1 parent a0f3949 commit a84306c

File tree

1 file changed

+11
-18
lines changed

1 file changed

+11
-18
lines changed

Search/MetaBinarySearch.js

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,33 @@
11
/**
22
* Meta Binary Search (also known as One-Pass Binary Search)
33
*
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/
95
*
6+
* Works on sorted arrays by using bit manipulation to perform binary search in a single pass.
107
* Time Complexity: O(log N)
118
* Space Complexity: O(1)
129
*
13-
* @param {number[]} arr - A sorted array to search within.
10+
* @param {number[]} arr - A sorted array.
1411
* @param {number} target - The element to search for.
1512
* @returns {number} - Index of the target if found, otherwise -1.
1613
*/
17-
18-
function metaBinarySearch(arr, target) {
19-
let n = arr.length;
14+
function MetaBinarySearch(arr, target) {
15+
const n = arr.length;
2016
if (n === 0) return -1;
2117

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);
2821
if (newPos < n && arr[newPos] <= target) {
29-
pos = newPos; // move to that position
22+
pos = newPos;
3023
}
31-
bit >>= 1; // move to the next bit
3224
}
3325

3426
return arr[pos] === target ? pos : -1;
3527
}
3628

37-
export { metaBinarySearch };
29+
export {MetaBinarySearch };
30+
3831

3932
// Example usage:
4033
// console.log(metaBinarySearch([1, 3, 5, 7, 9, 11], 7)); // Output: 3

0 commit comments

Comments
 (0)