Skip to main content

You have given an array in which numbers are first increasing and then decreasing. Find the maximum element in O(log n).

An integer array with unique elements has the following property – elements initially are in increasing order till a point after which they start to decrease. Implement a function to find the index of the maximum element in the array in less than linear time, i.e., O(n).

Example:
Input: array = {1, 3, 5, 7, 9, 8, 6, 4} Output: max index = 4

public class Array1 {
public int fun(int arr[], int low, int high) {
int index = -1;
if (low < high) {
int mid = low + ((high - low) / 2);
if (arr[mid] > arr[mid + 1] && arr[mid] > arr[mid - 1]) {
index = mid;
return index;
}
if (arr[mid] > arr[mid - 1]) {
return fun(arr, mid, high);
}
if (arr[mid] > arr[mid + 1]) {
return fun(arr, low, mid);
}
}
return index;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[] = { 1, 3, 5, 7, 9, 8, 6, 4 };
int arr2[] = null;
Array1 a = new Array1();
int maxIndex = a.fun(arr, 0, arr.length - 1);
System.out.println("Max Index : " + maxIndex
+ ". Max Element value is : " + arr[maxIndex]);
}
}
view raw gistfile1.txt hosted with ❤ by GitHub
Max Index : 4.  Max Element value is : 9

Comments

Popular posts from this blog

Greedy algorithms for Job Scheduling

In this programming problem and the next you'll code up the greedy algorithms from lecture for minimizing the weighted sum of completion times.. This file describes a set of jobs with positive and integral weights and lengths. It has the format [number_of_jobs] [job_1_weight] [job_1_length] [job_2_weight] [job_2_length] ... For example, the third line of the file is "74 59", indicating that the second job has weight 74 and length 59. You should NOT assume that edge weights or lengths are distinct. Your task in this problem is to run the greedy algorithm that schedules jobs in decreasing order of the difference (weight - length). This algorithm is not always optimal. IMPORTANT: if two jobs have equal difference (weight - length), you should schedule the job with higher weight first. Beware: if you break ties in a different way, you are likely to get the wrong answer. You should report the sum of weighted completion times of the resulting schedule --- a posi...

Integer comparison using == gets tricky between -128 to 127.

Integer i=45;                                                                                                                                   Integer k=45;         System.out.println("i.hashcode= "+i.hashCode());         System.out.println("k.hashcode= "+k.hashCode());         System.out.println(i==k);         System.out.println(i.equals(k)); Out Put: i.hashcode= 45 k.hashcode= 45 true true Great, it seems work fine! now change the value of i=k=201.         Integer i=201;     ...