forked from sPredictorX1708/Ultimate-Java-Resources
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTernarySearch.java
More file actions
45 lines (36 loc) · 874 Bytes
/
TernarySearch.java
File metadata and controls
45 lines (36 loc) · 874 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
class TERNARY {
// Function to perform Ternary Search
static int ternarySearch(int l, int r, int key, int array[]){
while (l<=r){
// Find the mid1 and mid2
int mid1 = l + (r - l) / 3;
int mid2 = r - (r - l) / 3;
// Check if key is present at any mid
if (array[mid1] == key) {
return mid1;
}
if (array[mid2] == key) {
return mid2;
}
/* Since key is not present at mid,
check in which side it is present
and repeat the Search operation
in that region */
if (key < array[mid1]) {
// The key lies in between l and mid1
r = mid1 - 1;
}
else if (key > array[mid2]) {
// The key lies in between mid2 and r
l = mid2 + 1;
}
else {
// The key lies in between mid1 and mid2
l = mid1 + 1;
r = mid2 - 1;
}
}
// Key not found
return -1;
}
}