Skip to content

Commit fea90dd

Browse files
authored
Merge pull request AllAlgorithms#52 from Arthur-Justino/master
Ternary search
2 parents 44b5b50 + b616893 commit fea90dd

1 file changed

Lines changed: 20 additions & 0 deletions

File tree

searches/TernarySearch.java

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
int ternary_search(int l,int r, int x)
2+
{
3+
if(r>=l)
4+
{
5+
int mid1 = l + (r-l)/3;
6+
int mid2 = r - (r-l)/3;
7+
if(ar[mid1] == x)
8+
return mid1;
9+
if(ar[mid2] == x)
10+
return mid2;
11+
if(x<ar[mid1])
12+
return ternary_search(l,mid1-1,x);
13+
else if(x>ar[mid2])
14+
return ternary_search(mid2+1,r,x);
15+
else
16+
return ternary_search(mid1+1,mid2-1,x);
17+
18+
}
19+
return -1;
20+
}

0 commit comments

Comments
 (0)