Skip to content

Commit 2fb59eb

Browse files
committed
Added ternary search implementation
fixes TheAlgorithms#96
1 parent 8917e41 commit 2fb59eb

File tree

1 file changed

+52
-0
lines changed

1 file changed

+52
-0
lines changed

Searches/TernarySearch.java

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
2+
/**
3+
* Ternary search is a divide-and-conquer algorithm to determine the position of
4+
* a specific value in a sorted array
5+
*
6+
*/
7+
8+
public class TernarySearch {
9+
/** call function **/
10+
public static int ternarySearch(int[] A, int value) {
11+
return ternarySearch(A, value, 0, A.length - 1);
12+
}
13+
14+
/** TernarySearch function **/
15+
public static int ternarySearch(int[] A, int value, int start, int end) {
16+
if (start > end)
17+
return -1;
18+
19+
/** First boundary: add 1/3 of length to start **/
20+
int mid1 = start + (end - start) / 3;
21+
/** Second boundary: add 2/3 of length to start **/
22+
int mid2 = start + 2 * (end - start) / 3;
23+
24+
if (A[mid1] == value)
25+
return mid1;
26+
else if (A[mid2] == value)
27+
return mid2;
28+
/** Search 1st third **/
29+
else if (value < A[mid1])
30+
return ternarySearch(A, value, start, mid1 - 1);
31+
/** Search 3rd third **/
32+
else if (value > A[mid2])
33+
return ternarySearch(A, value, mid2 + 1, end);
34+
/** Search middle third **/
35+
else
36+
return ternarySearch(A, value, mid1, mid2);
37+
}
38+
39+
/** Main method **/
40+
public static void main(String[] args) {
41+
int arr[] = { 2, 5, 15, 24, 31, 47, 59, 61, 79, 97 };
42+
int elementToBeSearched = 24;
43+
44+
int result = ternarySearch(arr, elementToBeSearched);
45+
46+
if (result == -1)
47+
System.out.println("\n" + elementToBeSearched + " element not found");
48+
else
49+
System.out.println("\n" + elementToBeSearched + " element found at position " + result);
50+
51+
}
52+
}

0 commit comments

Comments
 (0)