Repository navigation
Expand file tree
/
Copy pathexponentialSearch.java
More file actions
55 lines (45 loc) · 1.91 KB
/
Copy pathexponentialSearch.java
File metadata and controls
55 lines (45 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*Exponential Search Description:it is a searching algorithm that is used to find a specific element
within a sorted array or list.
It works by first identifying a range in which the target element is likely to be located
and then performing a binary search within that range.
Exponential search is particularly useful when dealing with very large data sets or
when the target element is far from the beginning of the array.
for more information:https://en.wikipedia.org/wiki/Exponential_search */
public class ExponentialSearch {
public static int exponentialSearch(int[] arr, int target) {
int n = arr.length;
// If the target is the first element, return 0
if (arr[0] == target) {
return 0;
}
int i = 1;// Find the range for binary search
while (i < n && arr[i] <= target) {
i *= 2;
}
// Perform binary search within the found range
return binarySearch(arr, target, i / 2, Math.min(i, n - 1));
}
private 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; // Element found
} else if (arr[mid] < target) {
left = mid + 1; // Search the right half
} else {
right = mid - 1; // Search the left half
}
}
return -1; // Element not found
}
public static void main(String[] args) {
int[] arr = {2, 4, 6, 8, 10, 12, 14, 15, 18, 20};
int target = 11;
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");
}
}
}