Skip to content

Commit 014bfda

Browse files
committed
Fixed bug with an infinite loop when an array doesn't contain a key
Fulfilled the code style request
1 parent c002090 commit 014bfda

File tree

1 file changed

+16
-8
lines changed

1 file changed

+16
-8
lines changed

Searches/src/search/IterativeTernarySearch.java

+16-8
Original file line numberDiff line numberDiff line change
@@ -34,19 +34,26 @@ public class IterativeTernarySearch implements SearchAlgorithm {
3434
public <T extends Comparable<T>> int find(T[] array, T key) {
3535
int left = 0;
3636
int right = array.length - 1;
37-
while (true) {
37+
38+
while (right > left) {
39+
3840
int leftCmp = array[left].compareTo(key);
3941
int rightCmp = array[right].compareTo(key);
4042
if (leftCmp == 0) return left;
4143
if (rightCmp == 0) return right;
4244

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+
4548

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+
}
4854
}
4955

56+
return -1;
5057
}
5158

5259

@@ -64,11 +71,12 @@ public static void main(String[] args) {
6471
IterativeTernarySearch search = new IterativeTernarySearch();
6572
int atIndex = search.find(integers, shouldBeFound);
6673

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));
6976

7077
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));
7280

7381
}
7482

0 commit comments

Comments
 (0)