1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47
|
#include<iostream>
using namespace std;
int ternary_search(int[], int, int, int);
int precval=1;
int main()
{
int n,arr[100],target;
cout<<"\t\t\tTernary Search\n\n"<<endl;
//cout<<"This program will find max element in an unidomal array."<<endl;
cout<<"How many integers: ";
cin>>n;
for(int i=0;i<n;i++)
cin>>arr[i];
cout<<endl<<"The max number in the array is: ";
int res=ternary_search(arr,0,n-1,precval)+0;
cout<<res<<endl;
return 0;
}
int ternary_search(int arr[],int left,int right,int precval)
{
if(right-left<=precval)
return (arr[right]>arr[left])?arr[right]:arr[left] ;
int first_third=(left*2+right)/3;
int last_third=(left+right*2)/3;
if(arr[first_third]<arr[last_third])
return ternary_search(arr,first_third,right,precval);
else
return ternary_search(arr,left,last_third,precval);
}
| |