如何在 java 中仅使用 1 个参数在 int 数组中实现递归二进制搜索?它试过了,但我的代码不起作用。我实现了一个类,它的实例是具有数组和计数变量的对象,以检测数组中有多少元素。知道如何仅使用 1 个参数来实现递归二进制搜索吗?
public class LinearSortedArray {
int count;
int[] a;
public LinearSortedArray() {
count = 0;
}
public LinearSortedArray(int size) {
count = 0;
a = new int[size];
}
public static int[] copyingMethod(int startPoint, int endPoint,
LinearSortedArray arrayObj) {
int[] copyingArray = new int[endPoint - startPoint];
int j = startPoint;
for (int i = 0; i < copyingArray.length; i++) {
copyingArray[i] = arrayObj.a[j];
j++;
}
return copyingArray;
}
public int binarySearchRec(int x) {
if (count == 0) {
return -1;
}
int pivot = count / 2;
LinearSortedArray newArrayObj;
if (x > a[pivot]) {
newArrayObj = new LinearSortedArray(count - pivot);
newArrayObj.count = newArrayObj.a.length;
newArrayObj.a = copyingMethod(pivot, count, this);
for (int i = 0; i < newArrayObj.a.length; i++) {
System.out.print(newArrayObj.a[i]);
System.out.print(" ");
}
System.out.println();
return pivot + newArrayObj.binarySearchRec(x);
} else if (x < a[pivot]) {
newArrayObj = new LinearSortedArray(pivot);
newArrayObj.count = newArrayObj.a.length;
newArrayObj.a = copyingMethod(0, pivot, this);
for (int i = 0; i < newArrayObj.a.length; i++) {
System.out.print(newArrayObj.a[i]);
System.out.print(" ");
}
System.out.println();
return newArrayObj.binarySearchRec(x);
} else {
return pivot;
}
}
}
PS:数组已经排序