Skip to content

Commit 98557f2

Browse files
authored
Added Ternary Search Algorithm in C.
1 parent e545443 commit 98557f2

1 file changed

Lines changed: 27 additions & 0 deletions

File tree

TernarySearch/C/ternary.c

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
// 'low' is the lower index
2+
// 'high' is the upper index
3+
// 'key' is the element to be searched
4+
int Ternary_search(inr ar[] , int low , int high , int key)
5+
{
6+
if(high>=low)
7+
{
8+
int mid1 = low + (high - low)/3;
9+
int mid2 = high - (high -low )/3;
10+
11+
if(ar[mid1] == x)
12+
return mid1; // returning mid1 if key is found at mid1 position
13+
if(ar[mid2] == x)
14+
return mid2; // returning mid1 if key is found at mid1 position
15+
16+
if(key>ar[mid2])
17+
return Ternarysearch(mid2+1,r,x); //if key element is in the right potion
18+
19+
else if(key<ar[mid1])
20+
return Ternarysearch(l,mid1-1,x); //if key element is in the left potion
21+
22+
else
23+
return Ternarysearch(mid1+1,mid2-1,x); //if key element is in the middle potion
24+
25+
}
26+
return -1; //return -1 if the key element is not found.
27+
}

0 commit comments

Comments
 (0)