Skip to content

Commit 49d2510

Browse files
authored
Create MetaBinarySearch.java
1 parent d868982 commit 49d2510

File tree

1 file changed

+43
-0
lines changed

1 file changed

+43
-0
lines changed

MetaBinarySearch.java

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
public class MetaBinarySearch {
2+
3+
// Function to perform Meta Binary Search
4+
public static int metaBinarySearch(int[] arr, int target) {
5+
int n = arr.length;
6+
int left = 0;
7+
int right = n - 1;
8+
9+
// Calculate the number of bits required for the maximum index
10+
int maxBits = (int) Math.ceil(Math.log(n) / Math.log(2));
11+
12+
// Iterate over the bit length
13+
for (int i = maxBits - 1; i >= 0; i--) {
14+
int mid = left + (1 << i);
15+
16+
// Check if mid index is within bounds
17+
if (mid < n && arr[mid] <= target) {
18+
left = mid; // move to the right half if condition is true
19+
}
20+
}
21+
22+
// Check if we have found the target
23+
if (arr[left] == target) {
24+
return left;
25+
}
26+
27+
// If target not found
28+
return -1;
29+
}
30+
31+
// Main function to test the Meta Binary Search
32+
public static void main(String[] args) {
33+
int[] sortedArray = {1, 3, 5, 7, 9, 11, 13, 15, 17, 19, 21};
34+
int target = 13;
35+
36+
int result = metaBinarySearch(sortedArray, target);
37+
if (result != -1) {
38+
System.out.println("Target element " + target + " found at index: " + result);
39+
} else {
40+
System.out.println("Target element " + target + " not found in the array.");
41+
}
42+
}
43+
}

0 commit comments

Comments
 (0)