Skip to content

Commit 6807e7e

Browse files
committed
Added Ternary Search
1 parent 8b29c6c commit 6807e7e

File tree

1 file changed

+74
-0
lines changed

1 file changed

+74
-0
lines changed

Searches/TernarySearch.java

+74
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
import java.util.Scanner;
2+
3+
public class TernarySearch{
4+
5+
/**
6+
* @param arr The **Sorted** array in which we will search the element.
7+
* @param value The value that we want to search for.
8+
* @return The index of the element if found.
9+
* Else returns -1.
10+
*/
11+
public static int ternarySearch(int[] arr, int value){
12+
return ternarySearch(arr, value, 0, arr.length - 1);
13+
}
14+
15+
/**
16+
* @param arr The **Sorted** array in which we will search the element.
17+
* @param key The value that we want to search for.
18+
* @param start The starting index from which we will start Searching.
19+
* @param end The ending index till which we will Search.
20+
* @return Returns the index of the Element if found.
21+
* Else returns -1.
22+
*/
23+
public static int ternarySearch(int[] arr, int key, int start, int end) {
24+
if (start > end){
25+
return -1;
26+
}
27+
/* First boundary: add 1/3 of length to start */
28+
int mid1 = start + (end - start) / 3;
29+
/* Second boundary: add 2/3 of length to start */
30+
int mid2 = start + 2 * (end - start) / 3;
31+
if (arr[mid1] == key) {
32+
return mid1;
33+
}
34+
else if (arr[mid2] == key) {
35+
return mid2;
36+
}
37+
38+
/* Search the first (1/3) rd part of the array.*/
39+
40+
else if (key < arr[mid1]) {
41+
return ternarySearch(arr, key, start, mid1 - 1);
42+
}
43+
/* Search 3rd (1/3)rd part of the array */
44+
45+
else if (key > arr[mid2]) {
46+
return ternarySearch(arr, key, mid2 + 1, end);
47+
}
48+
/* Search middle (1/3)rd part of the array */
49+
50+
else {
51+
return ternarySearch(arr, key, mid1, mid2);
52+
}
53+
}
54+
55+
public static void main(String[] args) {
56+
Scanner s = new Scanner(System.in);
57+
System.out.println("Enter number of elements in the array");
58+
int n = s.nextInt();
59+
int arr[] = new int[n];
60+
System.out.println("Enter the elements of the array");
61+
for (int i= 0; i < n; i++){
62+
arr[i] = s.nextInt();
63+
}
64+
System.out.println("Enter element to search for : ");
65+
int k = s.nextInt();
66+
int ans = ternarySearch(arr, k);
67+
if (ans == -1) {
68+
System.out.println(" The element is not present in the array.");
69+
}
70+
else {
71+
System.out.println("The element is present at the position" + ans);
72+
}
73+
}
74+
}

0 commit comments

Comments
 (0)