Skip to content

Instantly share code, notes, and snippets.

@viniru
Created May 28, 2018 09:10
Show Gist options
  • Save viniru/6f134fecc98a15465bae2149ef89a3f7 to your computer and use it in GitHub Desktop.
Save viniru/6f134fecc98a15465bae2149ef89a3f7 to your computer and use it in GitHub Desktop.
You are a given a unimodal array of n distinct elements, meaning that its entries are in increasing order up until its maximum element, after which its elements are in decreasing order. Give an algorithm to compute the maximum element that runs in O(log n) time
public class Unimodal {
public static void unimodal(int a[],int l,int h)
{
int mid = (l+h)/2;
if(a[mid] < a[mid+1])
{
if(a[mid+1] > a[mid+2])
{
System.out.println("The max element is : "+a[mid+1]);
System.exit(0);
}
else unimodal(a,mid+1,h);
}
else unimodal(a,l,mid);
}
public static void main(String args[])
{
int a[]={1,2,3,1};
unimodal(a,0,a.length-1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment