wu :: forums
« wu :: forums - Finding one local minima. »

Welcome, Guest. Please Login or Register.
May 15th, 2024, 4:58am

RIDDLES SITE WRITE MATH! Home Home Help Help Search Search Members Members Login Login Register Register
   wu :: forums
   riddles
   cs
(Moderators: Icarus, william wu, Grimbal, SMQ, ThudnBlunder, Eigenray, towr)
   Finding one local minima.
« Previous topic | Next topic »
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print
   Author  Topic: Finding one local minima.  (Read 1773 times)
bazinga
Junior Member
**





   


Gender: male
Posts: 53
Finding one local minima.  
« on: Mar 28th, 2011, 8:43am »
Quote Quote Modify Modify

Suppose we are given an array A[1 .. n] with the special property that A[1] ≥ A[2] and
A[n − 1] ≤ A[n]. We say that an element A[x] is a local minimum if it is less than or equal
to both its neighbors, or more formally, if A[x − 1] ≥ A[x] and A[x] ≤ A[x + 1]. For example,
there are five local minima in the following array:
9 7 7 2 1 3 7 5 4 7 3 3 4 8 6 9
We can obviously find a local minimum in O(n) time by scanning through the array. Describe
and analyze an algorithm that finds a local minimum in O(log n) time
 
Source
QuestionNumber:11
Would this java code solve it correctly?

Code:

public int getOneLocalMinimum(int lowIndex, int highIndex)  {
 
 
if (lowIndex > highIndex) {
 
 
 
return -1;
 
 
}
 
 
if (lowIndex == highIndex) {
 
 
 
return lowIndex;
 
 
}
 
 
if (lowIndex + 1 == highIndex) {
 
 
 
if (elements[lowIndex] < elements[highIndex]) {
 
 
 
 
return lowIndex;
 
 
 
}
 
 
 
return highIndex;
 
 
}
 
 
int midIndex = (lowIndex + highIndex) / 2;
 
 
if ((elements[midIndex] <= elements[midIndex - 1])
 
 
 
 
&& (elements[midIndex] <= elements[midIndex + 1])) {
 
 
 
return midIndex;
 
 
}
 
 
if (elements[midIndex] >= elements[midIndex + 1]) {
 
 
 
return getOneLocalMinimum(midIndex, highIndex);
 
 
} else {
 
 
 
return getOneLocalMinimum(lowIndex, midIndex);
 
 
}
IP Logged
Pages: 1  Reply Reply Notify of replies Notify of replies Send Topic Send Topic Print Print

« Previous topic | Next topic »

Powered by YaBB 1 Gold - SP 1.4!
Forum software copyright © 2000-2004 Yet another Bulletin Board