所以,我试图让我的binarySearch 工作,但它没有返回正确的搜索项。有人有主意吗?但它总是返回接近该项目的值。我知道问题出在二元搜索方法中的 while 循环上。
public class Sort {
static int item;
static Scanner console = new Scanner(System.in);
public static void main(String[] args) {
int[] list = new int[500];
for (int c = 0; c < 500; c++){
Random r = new Random();
list[c] = r.nextInt(1000);
}
int l = list.length;
System.out.print("Enter a search element: ");
System.out.println();
item = console.nextInt();
insertionSort(list, l);
}
public static int binarySearch(int[] list, int l,
int searchItem){
int first = 0;
int last = l - 1;
int mid = 0;
boolean found = false;
while (first <= last && !found)
{
mid = (first + last) / 2;
if (list[mid] == searchItem)
found = true;
else if (list[mid] > searchItem)
last = mid - 1;
else
first = mid + 1;
}
if (found)
return mid;
else
return 0;
}
public static void insertionSort(int[] list, int l){
int first, location;
int temp;
for (first = 1; first < l; first++){
if (list[first] < list[first - 1]){
temp = list[first];
location = first;
do {
list[location] = list[location - 1];
location--;
}
while(location > 0 && list[location - 1] > temp);
list[location] = temp;
}
}
System.out.println(binarySearch(list, l, item));
}
}
感谢您的帮助!
最佳答案
您需要返回 mid + 1,因为索引从 0 开始。
因此,如果您有 1,2,3 个元素,并且如果您尝试查找 2,它将返回 1,因为 array[1] 指向 2。因此,如果您返回 2,则意味着您在第二个位置找到了该元素.
关于java - binarySort 方法未返回正确项目的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27175164/