//Binary search : Time Complexity O(log n)
#include<bits/stdc++.h>
using namespace std;
int maximumElement(int a[], int low, int high)
{
if(low == high)
return a[low];
if((low+1 == high) && a[low] >= a[high]) // When array size is two
return a[low];
if((low+1 == high) && a[low] < a[high]) // When array size is two
return a[high];
int mid = (low+high)/2;
if(a[mid-1] < a[mid] && a[mid] > a[mid+1])
return a[mid];
else if(a[mid] < a[mid-1] && a[mid] > a[mid+1])
return maximumElement(a, low, mid-1);
else
return maximumElement(a, mid+1, high);
}
int main()
{
int n;
cout << "Enter Array Size :: ";
cin >> n;
int a[n];
cout << "Enter Array Element :: ";
for(int i=0;i<n;i++)
cin >> a[i];
int mx = maximumElement(a, 0, n-1);
cout << "\nMaximum Element :: " << mx << "\n";
return 0;
}
Comments
Post a Comment