Skip to content

Create MetaBinarySearch.java #5958

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions src/main/java/com/thealgorithms/searches/MetaBinarySearch.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package com.thealgorithms.searches;

public class MetaBinarySearch {

/**
* Perform Meta Binary Search on a sorted array.
*
* @param arr The sorted array to search.
* @param target The target element to search for.
* @return The index of the target element if found, -1 otherwise.
*/
public int metaBinarySearch(int[] arr, int target) {
int n = arr.length;
int left = 0;
int right = n - 1;

// Calculate the number of bits required for the maximum index
int maxBits = (int) Math.ceil(Math.log(n) / Math.log(2));

// Iterate over the bit length
for (int i = maxBits - 1; i >= 0; i--) {
int mid = left + (1 << i);

// Check if mid index is within bounds
if (mid < n && arr[mid] <= target) {
left = mid; // move to the right half if condition is true
}
}

// Check if we have found the target
if (left < n && arr[left] == target) {
return left;
}

// If target not found
return -1;
}
}
Loading