-
Notifications
You must be signed in to change notification settings - Fork 101
/
Copy pathTernarySearch.cpp
66 lines (51 loc) · 1.12 KB
/
TernarySearch.cpp
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
#include<iostream>
using namespace std;
int ternary_search(int arr[], int l, int r, int key)
{
if (l<=r)
{
int m1 = l + (r - l) / 3;
int m2 = r - (r - l) / 3;
if (arr[m1]==key)
{
return m1;
}
if (arr[m2]==key)
{
return m2;
}
if (key < arr[m1])
{
return ternary_search(arr, l, m1 - 1, key);
}
else if (key > arr[m2])
{
return ternary_search(arr, m2 + 1, r, key);
}
else
{
return ternary_search(arr, m1 + 1, m2 - 1, key);
}
}
return -1;
}
int main()
{
int n, i, key, res;
cout<<"Enter the no. of elements: ";
cin>>n;
int arr[n];
cout<<"Enter elements: ";
for(i=0;i<n;i++)
{
cin>>arr[i];
}
cout<<"\nEnter element to search: ";
cin>>key;
res=ternary_search(arr, 0, n-1, key);
if(res==-1)
cout<<"\nElement doesn't exist..!!";
else
cout<<"\nElement is present at index "<<res;
return 0;
}