Skip to content
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

Create Exponential Search #98

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
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
36 changes: 36 additions & 0 deletions Exponential Search
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
public class ExponentialSearch {
public static int exponentialSearch(int[] arr, int target) {
int bound = 1;
while (bound < arr.length && arr[bound] < target) {
bound *= 2;
}
int left = bound / 2;
int right = Math.min(bound, arr.length - 1);
return binarySearch(arr, target, left, right);
}

public static int binarySearch(int[] arr, int target, int left, int right) {
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == target) {
return mid;
} else if (arr[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}

public static void main(String[] args) {
int[] arr = {2, 5, 8, 12, 16, 23, 38, 42, 56, 72, 91};
int target = 23;
int index = exponentialSearch(arr, target);
if (index != -1) {
System.out.println("Element found at index: " + index);
} else {
System.out.println("Element not found in the array.");
}
}
}