File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 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+ }
You can’t perform that action at this time.
0 commit comments