【发布时间】:2020-11-05 11:00:42
【问题描述】:
所以,我正在开发一个旨在在排序数组中查找枢轴点的程序,并且我正在使用二进制搜索,因为它需要 OlogN 的大 O。我一直在做一些 JUnit 测试,我注意到我的代码没有返回正确的值。当我单步执行代码时,它会得到正确的值,但会继续运行,然后返回错误的答案?我已经做了很多笔和纸测试,理论上它应该返回数字。
我正在做的测试是检查如果索引位于中间左侧,程序将如何响应。 另外,当我进行测试以检查索引是否在中间的右侧时,我会得到无限递归?
我不是在寻求解决方案,而是指向某事或某处的指针,我可能会遗漏某事,因为作为编码人员,我意识到我可能很难批评自己的代码。
* Author: XXX
*
* This program is designed to find the pivot point in an array sorted in ascending order
* that is rotated at some pivot unknown to you beforehand.
*/
package algorithmAssignment;
public class pivotFinder {
public static void main(String[] args) {
// testing
int[] arr = new int[] {26, 28, 32, 1, 5, 6, 9, 10, 22};
int result = findPivot(arr, arr.length - 1, 0, arr.length/2);
// expected index of 3
System.out.println(result);
}
static int findPivot(int[] arr, int max, int min, int pivot) { // feeding in arr, max, min, and pivot point
// base case
if (max - min < 1) {
return pivot;
}
// binary search
if (arr[pivot] < arr[max]) {
findPivot(arr, pivot, min, pivot / 2); // return the arr, the pivot as the new max, and the new pivot
} else {
findPivot(arr, max, pivot, max - (pivot / 2)); // return the arr, the pivot as the new min, and the new
// pivot
}
return pivot; //unsure why I need this
}
}
另外,为什么我需要最后一行返回枢轴?我正在使用 eclipse,它说该方法必须返回一种 int,但它不是已经这样做了吗?我想知道这是否是我的问题。
【问题讨论】:
标签: java sorting binary-search