-
Notifications
You must be signed in to change notification settings - Fork 19.7k
/
Copy pathExponentalSearch.java
51 lines (46 loc) · 1.59 KB
/
ExponentalSearch.java
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
package com.thealgorithms.searches;
import com.thealgorithms.devutils.searches.SearchAlgorithm;
import java.util.Arrays;
/**
* ExponentialSearch is an algorithm that efficiently finds the position of a target
* value within a sorted array. It works by expanding the range to find the bounds
* where the target might exist and then using binary search within that range.
*
* <p>
* Worst-case time complexity: O(log n)
* Best-case time complexity: O(1) when the element is found at the first position.
* Average time complexity: O(log n)
* Worst-case space complexity: O(1)
* </p>
*
* <p>
* Note: This algorithm requires that the input array be sorted.
* </p>
*/
class ExponentialSearch implements SearchAlgorithm {
/**
* Finds the index of the specified key in a sorted array using exponential search.
*
* @param array The sorted array to search.
* @param key The element to search for.
* @param <T> The type of the elements in the array, which must be comparable.
* @return The index of the key if found, otherwise -1.
*/
@Override
public <T extends Comparable<T>> int find(T[] array, T key) {
if (array.length == 0) {
return -1;
}
if (array[0].equals(key)) {
return 0;
}
if (array[array.length - 1].equals(key)) {
return array.length - 1;
}
int range = 1;
while (range < array.length && array[range].compareTo(key) < 0) {
range = range * 2;
}
return Arrays.binarySearch(array, range / 2, Math.min(range, array.length), key);
}
}