Skip to content
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.");
}
}
}