Skip to content

Commit 94d3533

Browse files
committed
Added C++ code for ternary search
1 parent 405b286 commit 94d3533

File tree

1 file changed

+55
-0
lines changed

1 file changed

+55
-0
lines changed
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#include <iostream>
2+
using namespace std;
3+
int ternarySearch(int l, int r, int key, int ar[])
4+
5+
{
6+
while (r >= l) {
7+
8+
int mid1 = l + (r - l) / 3;
9+
int mid2 = r - (r - l) / 3;
10+
11+
if (ar[mid1] == key) {
12+
return mid1;
13+
}
14+
if (ar[mid2] == key) {
15+
return mid2;
16+
}
17+
18+
19+
if (key < ar[mid1]) {
20+
21+
// The key lies in between l and mid1
22+
r = mid1 - 1;
23+
}
24+
else if (key > ar[mid2]) {
25+
26+
// The key lies in between mid2 and r
27+
l = mid2 + 1;
28+
}
29+
else {
30+
31+
// The key lies in between mid1 and mid2
32+
l = mid1 + 1;
33+
r = mid2 - 1;
34+
}
35+
}
36+
return -1;
37+
}
38+
int main()
39+
{
40+
int len;
41+
cin>>len;
42+
int ar[len];
43+
for(int i=0;i<len;i++){
44+
cin>>ar[i];
45+
}
46+
int key;
47+
cin>>key;
48+
int l=0;
49+
int r=len-1;
50+
int p=0;
51+
p = ternarySearch(l, r, key, ar);
52+
53+
cout << "Index of "<<key<<" is " << p << endl;
54+
}
55+

0 commit comments

Comments
 (0)