8000 Merge pull request #28 from ltosh9802/master · sonwanigaurav/Java-Algorithms@3911456 · GitHub
[go: up one dir, main page]

Skip to content

Commit 3911456

Browse files
authored
Merge pull request darpanjbora#28 from ltosh9802/master
Added Java implementation of Ternay Search Algorithm
2 parents 9173120 + ea1775b commit 3911456

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed

Searching/TernaySearch.java

Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
import java.util.*;
2+
import java.io.*;
3+
class ternarysearch {
4+
5+
// Function to perform Ternary Search
6+
static int ternarySearch(int l, int r, int key, int ar[])
7+
8+
{
9+
while (r >= l) {
10+
11+
// Find the mid1 mid2
12+
int mid1 = l + (r - l) / 3;
13+
int mid2 = r - (r - l) / 3;
14+
15+
// Check if key is present at any mid
16+
if (ar[mid1] == key) {
17+
return mid1;
18+
}
19+
if (ar[mid2] == key) {
20+
return mid2;
21+
}
22+
23+
if (key < ar[mid1]) {
24+
25+
// The key lies in between l and mid1
26+
r = mid1 - 1;
27+
}
28+
else if (key > ar[mid2]) {
29+
30+
// The key lies in between mid2 and r
31+
l = mid2 + 1;
32+
}
33+
else {
34+
35+
// The key lies in between mid1 and mid2
36+
l = mid1 + 1;
37+
r = mid2 - 1;
38+
}
39+
}
40+
41+
// Key not found
42+
return -1;
43+
}
44+
45+
// Driver code
46+
public static void main(String args[])
47+
{
48+
int l, r, p, key;
49+
50+
// Get the array
51+
// Sort the array if not sorted
52+
int ar[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
53+
54+
// Starting index
55+
l = 0;
56+
57+
// length of array
58+
r = 9;
59+
60+
// Checking for 5
61+
62+
// Key to be searched in the array
63+
key = 5;
64+
65+
// Search the key using ternarySearch
66+
p = ternarySearch(l, r, key, ar);
67+
68+
// Print the result
69+
System.out.println("Index of " + key + " is " + p);
70+
71+
// Checking for 50
72+
73+
// Key to be searched in the array
74+
key = 50;
75+
76+
// Search the key using ternarySearch
77+
p = ternarySearch(l, r, key, ar);
78+
79+
// Print the result
80+
System.out.println("Index of " + key + " is " + p);
81+
}
82+
}

0 commit comments

Comments
 (0)
0