Java BinarySearch
•
Java
Can I get some help? I've tried many ways to make this work. I get array sorting and printing, but then my binary search function doesn't want to run and give me the correct results It always gives me - 1 Does it 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)); } }
Solution
You don't actually compare with array values stay
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 find the correct index, but what you do is you just compare the index number with your key, which is obviously incorrect When you write [mid], you actually compare your key with the number in the middle of the index
The last line of code is also a compilation error. It should be
System.out.println("Found " + key + " at " + binarySearch(a,key));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码