使用Java的数组排序和二进制搜索
我被要求对数组进行排序和搜索。数组的排序很简单,我的代码也很有效,但每当我尝试调用二进制搜索方法时,它对数组中的第一个元素有效,但结果是“-1”
我的完整代码如下:
public static void main(String[] args) {
int[] array = new int[5];
array[0] = 50;
array[1] = 40;
array[2] = 10;
array[3] = 20;
array[4] = 100;
sort(array, (array.length - 1));
for (int x = 0; x < array.length; x++) {
System.out.println(" " + array[x]);
}
System.out.println("");
System.out.println("Binary search (R): " + rBsearch(array, 0, (array.length), 20));
}
public static void sort(int[] a, int last) {
if (last > 0) {
int max = findMax(a, last);
swap(a, last, max);
sort(a, last - 1);
}
}
public static int rBsearch(int[] L, int low, int high, int k) {
int mid = (low + high) / 2;
if (low > high) {
return -1;
} else if (L[mid] == k) {
return mid;
} else if (L[mid] < k) {
return rBsearch(L, k, mid + 1, high);
} else {
return rBsearch(L, k, low, mid - 1);
}
}
public static int findMax(int[] arr, int last) {
int max = 0;
for (int i = 0; i <= last; i++) {
if (arr[i] > arr[max]) {
max = i;
}
}
return max;
}
public static void swap(int[] arr, int last, int max) {
int temp = arr[last];
arr[last] = arr[max];
arr[max] = temp;
}
# 1 楼答案
然后使用二进制搜索来搜索元素
Result of BinarySearch
# 2 楼答案
最简单的方法是: 将数组转换为列表:
Arrays.asList(array)
对于排序:
Collections#sort
搜索:
Collections#binarySearch
见this
# 3 楼答案
你搞错了二进制搜索间隔
# 4 楼答案
在以下几行中调用rBsearch方法时出错 而不是
你应该使用