Skip to content
This repository was archived by the owner on Jun 26, 2022. It is now read-only.

Commit 3cf3b9d

Browse files
Merge pull request #29 from ojas032/master
Added Ternary Search
2 parents 23c00ea + 5e39e08 commit 3cf3b9d

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

cpp/Ojas032_Ternary_Search.cpp

+47
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
#include<bits/stdc++.h>
2+
3+
using namespace std;
4+
5+
6+
int Ternary_Search(int arr[],int l,int r, int x)
7+
{
8+
if(r>=l)
9+
{
10+
int mid1 = l+(r-l)/3;
11+
int mid2 = r-(r-l)/3;
12+
if(arr[mid1]==x)
13+
return mid1;
14+
if(arr[mid2]==x)
15+
return mid2;
16+
if(x<arr[mid1])
17+
return Ternary_Search(arr,l,mid1-1,x);
18+
else if(x>arr[mid2])
19+
return Ternary_Search(arr,mid2+1,r,x);
20+
else
21+
return Ternary_Search(arr,mid1+1,mid2-1,x);
22+
23+
}
24+
return -1;
25+
}
26+
27+
28+
int main(){
29+
int n,x;
30+
cout<<"Enter the no of Elements:\n";
31+
cin>>n;
32+
int a[n];
33+
cout<<"Enter the elements:\n";
34+
for(int i=0;i<n;i++){
35+
cin>>a[i];
36+
}
37+
cout<<"Enter the element to be searched in the array:\n";
38+
cin>>x;
39+
int p=Ternary_Search(a,0,n-1,x);
40+
if(p==-1)
41+
cout<<"Element does not exist\n";
42+
else{
43+
cout<<"Element found at index "<<p+1<<"\n";
44+
}
45+
46+
47+
}

0 commit comments

Comments
 (0)