我正在尝试为二进制搜索方法排序数组,但我不确定采用哪种方法对数组进行排序。我尝试过Arrays.sort和Collections,但是我尝试运行程序时都会返回异常。查找数组中的一些元素会返回值,但是对于其他值,例如数组中的(3 5)的输入,其中它返回值5但是一旦它被排序我想要值7。我不知道采取哪种方法,或者我是否走在正确的道路上,所以我将不胜感激任何帮助!
/**
* Binary search to fix data sets issues
*/
import java.util.Arrays;
import java.util.Collections;
import java.util.Scanner;
public class BinarySearch {
/** Use binary search to find the key in the list */
public static int binarySearch(int[] list, int key) {
int low = 0;
int high = list.length - 1;
while (high >= low) {
int mid = (low + high) / 2;
if (key < list[mid])
high = mid - 1;
else if (key == list[mid])
return mid;
else
low = mid + 1;
}
return -low - 1;
}
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int set = in.nextInt();
int key = in.nextInt();
int[][] datasets = { {},
{1,2,3,5,8,13,21,34,55,89},
{-81, -72, -63, -54, -45, -36, -27, -18, -9, 0},
{21, 34, 72, -63, 8, 5, -13, -27, -18, 1, 0, 2}
};
//Arrays.sort(datasets);
//Collections.sort(datasets);
System.out.println("Searching for key " + key +
" in data set " + set +
" returned " + binarySearch(datasets[set], key));
}
}