File tree Expand file tree Collapse file tree 1 file changed +38
-0
lines changed
src/main/java/com/thealgorithms/searches Expand file tree Collapse file tree 1 file changed +38
-0
lines changed Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments