Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BinarySearch

Tags:

java

Can I get some help please? I have tried many methods to get this to work i got the array sorted and to print but after that my binary search function doesnt want to run and give me right results. It always gives me -1. Any help?

public class BinarySearch {
public static final int NOT_FOUND = -1;
public static int binarySearch(double[] a, double key) {
    int low = 0;
    int high = a.length -1;
    int mid;
    while (low<=high) {
        mid = (low+high) /2;
        if (mid > key) 
            high = mid -1;
        else if (mid < key) 
            low = mid +1;
        else 
            return mid;
    }
    return NOT_FOUND;
}
public static void main(String[] args) {
    double key = 10.5, index;
    double a[] ={10,5,4,10.5,30.5};
    int i;
    int l = a.length;
    int j;
    System.out.println("The array currently looks like");
    for (i=0; i<a.length; i++)
        System.out.println(a[i]);
    System.out.println("The array after sorting looks like");
    for (j=1; j < l; j++) {
        for (i=0; i < l-j; i++) {
            if (a[i] > a[i+1]) {
                double temp = a[i];
                a[i] = a[i+1];
                a[i+1] = temp;
            }
        }
    }
    for (i=0;i < l;i++) {
        System.out.println(a[i]);
    }
    System.out.println("Found " + key + " at " + binarySearch(double a[], key));
}   
}
like image 434
user1686765 Avatar asked Sep 20 '12 17:09

user1686765


2 Answers

you are not actually comparing with the array values. in

while (low <= high) {
      mid = (low + high) / 2;
      if (mid > key) {
          high = mid - 1;
      } else if (mid < key) {
          low = mid + 1;
      } else {
          return mid;
      }
}

Instead use this section

    while (low <= high) {
        mid = (low + high) / 2;
        if (a[mid] > key) {
            high = mid - 1;
        } else if (a[mid] < key) {
            low = mid + 1;
        } else {
            return mid;
        }
    }

You were correct to find the indexes, but what you were doing is that you were just comparing index number with your key, which is obviously incorrect. When you write a[mid] you will actually compare your key with the number which is at index mid.

Also the last line of code is giving compile error, it should be

System.out.println("Found " + key + " at " + binarySearch(a, key));
like image 91
Shades88 Avatar answered Sep 26 '22 13:09

Shades88


Here

    if (mid > key) 
        high = mid -1;
    else if (mid < key) 
        low = mid +1;
    else 
        return mid;

You're comparing index to a value (key) in array. You should instead compare it to a[mid]

And,

System.out.println("Found " + key + " at " + binarySearch(double a[], key));

Should be

System.out.println("Found " + key + " at " + binarySearch(a, key));
like image 24
nullpotent Avatar answered Sep 25 '22 13:09

nullpotent