|
-
February 19th, 2009, 12:26 AM
#1
Binary Search Problem
I'm trying to implement a binary search.
Here is my code:
Code:
import java.util.Scanner;
import java.io.*;
public class test3
{
public static void main( String args[] )
{
System.out.println(binarySearch());
}
public static Boolean testMiddle(int middle)
{
int key = 37;
if (middle <= key) return true;
else return false;
}
public static int binarySearch()
{
int low=0;
int high = 40;
int middle = (low + high) / 2;
do
{
if (testMiddle(middle))
{
low = middle;
middle = (low + high) / 2;
}
else
{
high = middle;
middle = (low + high) / 2;
}
} while (low<high);
return middle;
}
}
Just imagine that there is some unknown key. (in this case it happens to be 37)
And the binarySearch method has to keep making calls to testMiddle to "zero in" on the key.
If the argument to testMiddle is <= the key, then it returns true. if it's greater, then it returns false.
My binarySearch method has problems. it goes into infiniteloops sometimes.
How do I need to modify it?
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|