I have this but the method isn't showing up on the object created in bluej. How can an do a binary search on an int array then output the found int?
public static int binarySearch(int a[], int element)
{
int first = 0;
int upto = a.length;
while (first < upto)
{
int mid = (first + upto) / 2; // Compute mid point.
if (element < a[mid])
{
upto = mid; // repeat search in bottom half.
} else if (element > a[mid])
{
first = mid + 1; // Repeat search in top half.
}
else
{
return mid; // Found it. return position
}
}
return -(first + 1); // Failed to find key
}
You made the method static . Therefore it most likely appears in the context menu of the class not of the object .
If you always returned found the int
you are looking for, you would just return element
every time. There would be no point doing a search. This method returns the index of the elements or the negative of the place it is inserted.
BTW: This code example has an old bug in the
int mid = (first + upto) / 2
which should read
int mid = (first + upto) >>> 1;
as it does in Arrays.binarySearch();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.