forked from HarshCasper/NeoAlgo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TernarySearch.java
92 lines (81 loc) · 2.1 KB
/
TernarySearch.java
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
import java.util.*;
public class Main
{
// Recursive Approach
static int ternarySearchRecursive (int arr[], int f, int left, int right)
{
if (left <= right)
{
int mid1 = left + (right - left) / 3;
int mid2 = right - (right - left) / 3;
if (arr[mid1] == f)
return mid1 + 1;
else if (arr[mid2] == f)
return mid2 + 1;
else if (f < arr[mid1])
return ternarySearchRecursive (arr, f, left, mid1 - 1);
else if (f > arr[mid2])
return ternarySearchRecursive (arr, f, mid2 + 1, right);
else
return ternarySearchRecursive (arr, f, mid1 + 1, mid2 - 1);
}
return -1;
}
// Iterative Approach
static int ternarySearch(int arr[], int f, int left, int right)
{ int found = -1;
while(left <= right)
{
int mid1 = left + (right - left) / 3;
int mid2 = right - (right - left) / 3;
if(arr[mid1] == f)
return mid1 + 1;
else if(arr[mid2] == f)
return mid2 + 1;
else if(f < arr[mid1])
right = mid1 - 1;
else if(f > arr[mid2])
left = mid2 + 1;
else
{
left = mid2 + 1;
right = mid2 - 1;
}
}
return found;
}
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
int i, n, left, right, f = -1, element;
System.out.println ("Enter length of array");
n = sc.nextInt ();
System.out.println ("Enter array elements");
int arr[] = new int[n];
for (i = 0; i < n; i++)
arr[i] = sc.nextInt ();
System.out.println ("Enter element to be searched");
element = sc.nextInt ();
Arrays.sort (arr);
left = 0;
right = n - 1;
f = ternarySearch(arr, element, left, right);
if (f != -1)
System.out.println ("Element found at " + (f));
else
System.out.println ("Element not found");
}
}
/*
Time Complexity - O(log3(N))
Sample I/O :
Input :
Enter length of array
4
Enter array elements
1 2 3 4
Enter element to be searched
4
Output :
Element found at 4
*/