-
Notifications
You must be signed in to change notification settings - Fork 19.7k
/
Copy pathIterativeTernarySearch.java
64 lines (56 loc) · 1.9 KB
/
IterativeTernarySearch.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
52
53
54
55
56
57
58
59
60
61
62
63
64
package com.thealgorithms.searches;
import com.thealgorithms.devutils.searches.SearchAlgorithm;
/**
* An iterative implementation of the Ternary Search algorithm.
*
* <p>
* Ternary search is a divide-and-conquer algorithm that splits the array into three parts
* instead of two, as in binary search. This implementation is iterative, reducing the overhead
* associated with recursive function calls. However, the recursive version can also be optimized
* by the Java compiler to resemble the iterative version, resulting in similar performance.
*
* <p>
* Worst-case performance: Θ(log3(N))<br>
* Best-case performance: O(1)<br>
* Average performance: Θ(log3(N))<br>
* Worst-case space complexity: O(1)
*
* <p>
* This class implements the {@link SearchAlgorithm} interface, providing a generic search method
* for any comparable type.
*
* @see SearchAlgorithm
* @see TernarySearch
* @since 2018-04-13
*/
public class IterativeTernarySearch implements SearchAlgorithm {
@Override
public <T extends Comparable<T>> int find(T[] array, T key) {
if (array == null || array.length == 0 || key == null) {
return -1;
}
if (array.length == 1) {
return array[0].compareTo(key) == 0 ? 0 : -1;
}
int left = 0;
int right = array.length - 1;
while (right > left) {
int leftCmp = array[left].compareTo(key);
int rightCmp = array[right].compareTo(key);
if (leftCmp == 0) {
return left;
}
if (rightCmp == 0) {
return right;
}
int leftThird = left + (right - left) / 3 + 1;
int rightThird = right - (right - left) / 3 - 1;
if (array[leftThird].compareTo(key) <= 0) {
left = leftThird;
} else {
right = rightThird;
}
}
return -1;
}
}