forked from AllAlgorithms/cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathternary_search.cpp
More file actions
64 lines (57 loc) · 1.26 KB
/
ternary_search.cpp
File metadata and controls
64 lines (57 loc) · 1.26 KB
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
// Ternary Search implemented in C++
//
// Binary search works for a sorted array.
// More documentation about the algorithm
//
// The All ▲lgorithms Project
//
// https://allalgorithms.com/cpp/category/algorithm
// https://github.com/allalgorithms/cpp
//
// Contributed by: Sriram Desai
// Github: @desai10
//
#include <iostream>
#include <vector>
using namespace std;
vector<int> ar;
int ternary_search(int l,int r, int x)
{
if(r>=l)
{
int mid1 = l + (r-l)/3;
int mid2 = r - (r-l)/3;
if(ar[mid1] == x)
return mid1;
if(ar[mid2] == x)
return mid2;
if(x<ar[mid1])
return ternary_search(l,mid1-1,x);
else if(x>ar[mid2])
return ternary_search(mid2+1,r,x);
else
return ternary_search(mid1+1,mid2-1,x);
}
return -1;
}
int main(int argc, char const *argv[])
{
int n, key;
cout << "Enter size of array: ";
cin >> n;
cout << "Enter array elements: ";
for (int i = 0; i < n; ++i)
{
int t;
cin>>t;
ar.push_back(t);
}
cout << "Enter search key: ";
cin>>key;
int res = ternary_search(0, n-1, key);
if(res != -1)
cout<< key << " found at index " << res << endl;
else
cout << key << " not found" << endl;
return 0;
}