@@ -34,19 +34,26 @@ public class IterativeTernarySearch implements SearchAlgorithm {
34
34
public <T extends Comparable <T >> int find (T [] array , T key ) {
35
35
int left = 0 ;
36
36
int right = array .length - 1 ;
37
- while (true ) {
37
+
38
+ while (right > left ) {
39
+
38
40
int leftCmp = array [left ].compareTo (key );
39
41
int rightCmp = array [right ].compareTo (key );
40
42
if (leftCmp == 0 ) return left ;
41
43
if (rightCmp == 0 ) return right ;
42
44
43
- int leftThird = left + (right - left ) / 3 ;
44
- int rightThird = right - (right - left ) /3 ;
45
+ int leftThird = left + (right - left ) / 3 + 1 ;
46
+ int rightThird = right - (right - left ) / 3 - 1 ;
47
+
45
48
46
- if (array [leftThird ].compareTo (key ) <= 0 ) left = leftThird ;
47
- else right = rightThird ;
49
+ if (array [leftThird ].compareTo (key ) <= 0 ) {
50
+ left = leftThird ;
51
+ } else {
52
+ right = rightThird ;
53
+ }
48
54
}
49
55
56
+ return -1 ;
50
57
}
51
58
52
59
@@ -64,11 +71,12 @@ public static void main(String[] args) {
64
71
IterativeTernarySearch search = new IterativeTernarySearch ();
65
72
int atIndex = search .find (integers , shouldBeFound );
66
73
67
- System .out .println (format ("Should be found: %d. Found %d at index %d. An array length %d"
68
- , shouldBeFound , integers [atIndex ], atIndex , size ));
74
+ System .out .println (format ("Should be found: %d. Found %d at index %d. An array length %d" ,
75
+ shouldBeFound , integers [atIndex ], atIndex , size ));
69
76
70
77
int toCheck = Arrays .binarySearch (integers , shouldBeFound );
71
- System .out .println (format ("Found by system method at an index: %d. Is equal: %b" , toCheck , toCheck == atIndex ));
78
+ System .out .println (format ("Found by system method at an index: %d. Is equal: %b" ,
79
+ toCheck , toCheck == atIndex ));
72
80
73
81
}
74
82
0 commit comments