Binary Search Help

Below is the coding for the binary search:

public class Binary_Search_

{

public int binarySearch(int arr[],int key)

{

int low=0;

int high=arr.length-1;

while(low<=high)

{

int middle=(low+high)/2;

if(key==arr[middle])

return middle;

else

if(key<arr[middle]) high=middle-1;

else low=middle+1;

}

return -1;//not found

}}

The only thing is that for the binary search the array must be sorted so what could I add to the start of the coding to quickly sort the array.

You must think this is a simple question but im new to java!>

[654 byte] By [Princea] at [2007-10-2 5:29:12]
# 1
Yes, you could sort the array before you started your search.Check the API for java.util.Arrays.sort(int []).
dev-AZa at 2007-7-16 1:30:50 > top of Java-index,Other Topics,Algorithms...
# 2

Another thing..

Try rethinking your algorithm through.

int middle=(low+high)/2

will not always hit the center/middle/sweet spot (or what you would call it) of your array.

If low was 2 and high was 5, your middle would be 3 (yes, 3), and if you are unlucky to have an array like this

1, 2, 3, 5, 7, 11, 13, 17, 19

your code would return -1 if you were searching for 5.

And that's just one of a jillion possibilities.

dev-AZa at 2007-7-16 1:30:50 > top of Java-index,Other Topics,Algorithms...
# 3

low + (high - low)/2

would this be ok?

Also how can I create an array that generates random numbers and then allow the user to type in a dialog box (or similar) the size of the array. I need to test the running time of the algorithm so I need to be able to get arrays of different sizes by just entering a number rather than changing the code.

Could you help please.

Thanx in advance

Princea at 2007-7-16 1:30:50 > top of Java-index,Other Topics,Algorithms...
# 4
I think your code is right!another idea:You can define a class and implement the interface Comparator ,then use the class java.util.Arrays provides the binarySearch function.
dreamseaa at 2007-7-16 1:30:50 > top of Java-index,Other Topics,Algorithms...