Skip to content

Commit f788fe3

Browse files
authored
Create MetaBinarySearch.java
1 parent be0b1d5 commit f788fe3

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
package com.thealgorithms.searches;
2+
3+
public class MetaBinarySearch {
4+
5+
/**
6+
* Perform Meta Binary Search on a sorted array.
7+
*
8+
* @param arr The sorted array to search.
9+
* @param target The target element to search for.
10+
* @return The index of the target element if found, -1 otherwise.
11+
*/
12+
public int metaBinarySearch(int[] arr, int target) {
13+
int n = arr.length;
14+
int left = 0;
15+
int right = n - 1;
16+
17+
// Calculate the number of bits required for the maximum index
18+
int maxBits = (int) Math.ceil(Math.log(n) / Math.log(2));
19+
20+
// Iterate over the bit length
21+
for (int i = maxBits - 1; i >= 0; i--) {
22+
int mid = left + (1 << i);
23+
24+
// Check if mid index is within bounds
25+
if (mid < n && arr[mid] <= target) {
26+
left = mid; // move to the right half if condition is true
27+
}
28+
}
29+
30+
// Check if we have found the target
31+
if (left < n && arr[left] == target) {
32+
return left;
33+
}
34+
35+
// If target not found
36+
return -1;
37+
}
38+
}

0 commit comments

Comments
 (0)