forked from recongamer/Hacktoberfest2021
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TernarySearch.cpp
53 lines (43 loc) · 1.01 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
#include <bits/stdc++.h>
using namespace std;
int ternarySearch(int l, int r, int key, int ar[])
{
if (r >= l) {
int mid1 = l + (r - l) / 3;
int mid2 = r - (r - l) / 3;
if (ar[mid1] == key) {
return mid1;
}
if (ar[mid2] == key) {
return mid2;
}
if (key < ar[mid1]) {
return ternarySearch(l, mid1 - 1, key, ar);
}
else if (key > ar[mid2]) {
return ternarySearch(mid2 + 1, r, key, ar);
}
else {
return ternarySearch(mid1 + 1, mid2 - 1, key, ar);
}
}
return -1;
}
int main()
{
int n ,l, r, p, key;
cin >> n ;
int *ar = new int[n] ;
// taking input array
for(int i = 0 ; i < n ;i++){
cin >> ar[i] ;
}
cout << "enter key ";
cin >> key ;
l = 0;
r = n;
cout << r ;
p = ternarySearch(l, r, key, ar);
// Print the result
cout << "Index of " << key << " is " << p << endl;
}