Here we can iterate through array to find maximum element in array by using Brute-Force method.
Its running time would be : O(n).
But still we can do it in a better way with much improved running time complexity i.e O(log(n)).
We can use binary search to solve this problem.
Please find below code in C++.
//Iterative method
int FindMax(vector<int> &aV,int aStart,int aEnd){
int lower=aStart;
int upper = aEnd;
int mid = (upper-lower)/2;
while(lower<=upper){
if(aV[mid]>aV[mid-1] && aV[mid]>aV[mid+1]){
cout<<"Found element"<<"\n";
return aV[mid];
}
else if(aV[mid]>aV[mid-1]){
// Search in second half
lower = mid+1;
mid=((upper-lower)/2)+lower;
cout<<"moving to 2nd part: lower: "<<lower<<" mid:"<<mid<<" upper: "<<upper<<"\n";
}else {
// Search in First half
upper = mid-1;
mid = ((upper-lower)/2)+lower;
cout<<"moving to 1st part: lower: "<<lower<<" mid:"<<mid<<"upper: "<<upper<<"\n";
}
}
cout<<"Could not find such element"<<"\n";
return -1;
}
Its running time would be : O(n).
But still we can do it in a better way with much improved running time complexity i.e O(log(n)).
We can use binary search to solve this problem.
Please find below code in C++.
//Iterative method
int FindMax(vector<int> &aV,int aStart,int aEnd){
int lower=aStart;
int upper = aEnd;
int mid = (upper-lower)/2;
while(lower<=upper){
if(aV[mid]>aV[mid-1] && aV[mid]>aV[mid+1]){
cout<<"Found element"<<"\n";
return aV[mid];
}
else if(aV[mid]>aV[mid-1]){
// Search in second half
lower = mid+1;
mid=((upper-lower)/2)+lower;
cout<<"moving to 2nd part: lower: "<<lower<<" mid:"<<mid<<" upper: "<<upper<<"\n";
}else {
// Search in First half
upper = mid-1;
mid = ((upper-lower)/2)+lower;
cout<<"moving to 1st part: lower: "<<lower<<" mid:"<<mid<<"upper: "<<upper<<"\n";
}
}
cout<<"Could not find such element"<<"\n";
return -1;
}
No comments:
Post a Comment