DuFFY0121
DuFFY0121

Reputation: 11

Using Binary Search to find a value in an Array (Java)

I need to use binary search to locate 45.3 in the array. Here's what I have so far.

public class Bsearch {
    public static final int NOT_FOUND = -1;

    public static int binarySearch(int[] a, int x) {
        int low = 0;
        int high = a.length - 1;
        int mid;
        while (low <= high) {
            mid = (low + high) / 2;
            if (a[mid].compareTo(x) < 0)
                low = mid + 1;
            else if (a[mid].compareTo(x) > 0)
                high = mid - 1;
            else
                return mid;
        }
        return NOT_FOUND;
    }

    public static void main(String[] args) {
        int SIZE = 6;
        int[] a = new Integer[SIZE] = { 10, -3, 5, 24, 45.3, 10.5 };
        System.out.println("45.3 Found" + binarySearch(a, 45.3));
    }
}

All my errors seem to be stemming from this area-

    int [] a = new Integer [ SIZE ]={ 10,-3,5,24,45.3,10.5 };
    System.out.println("45.3 Found" +binarySearch(a, 45.3));

All this is new to me so sorry for any obvious mistakes.

Upvotes: 1

Views: 1549

Answers (2)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31299

The problem is indeed in this line:

int[] a = new Integer[SIZE] = { 10, -3, 5, 24, 45.3, 10.5 };

There are a number of issues:

  1. You can't assign an Integer[] to an int[] variable. Change it to new int[]
  2. You can't put a floating point number in an array of integers; change your numbers 45.3 and 10.5 to integers.
  3. You have two options in Java: when you create a new array with the new operator, you either specify size of the array, or the contents.

So either:

int[] a = new int[SIZE];

Or

int[] a = new int[] { 10, -3, 5, 24, 45, 10 };

Both will work.


You have to decide whether you want to use primitive types (int) of class wrappers (Integer) and stick to it.

Your method binarySearch takes an int[] as a parameter, but you are using methods (compareTo) that are only available on Integer.

But actually, comparing is much simpler with primitive types:

       if (a[mid] < x)
            low = mid + 1;
        else if (a[mid] > x)
            high = mid - 1;
        else
            return mid;

Upvotes: 1

Prabhat
Prabhat

Reputation: 338

For binary search Data Array should be sorted, and sorted in the right order, but the array you are passing to binarySearch(int[] a, int x) is not sorted so first sort the array and then apply binary search on it. Also check your logic for binary search, you are comparing middle element with 0 it should be compared with the element to be searched(key)

while(high >= low) {
  int middle = (low + high) / 2;
  if(data[middle] == key) {
     return true;
  }
  if(data[middle] < key) {
  low = middle + 1;
  }
  if(data[middle] > key) {
  high = middle - 1;
  }
}

Upvotes: 1

Related Questions