二进制搜索输出不正确



我在数组上进行二进制搜索时遇到了问题。它运行,但我每次都得到不正确的输出。我不太清楚为什么。如果有人能帮忙,我们将不胜感激。

public class chapter7Assignment {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
int[] numbers = {1, 566, 18, 1, 8, 5, 18, 4, 3, 8};
int searchValue;
int foundValue;
System.out.print("Enter a value: ");
searchValue = scanner.nextInt();
foundValue = searchMethod(numbers, searchValue);
if (value == -1) {
System.out.println("Didn't find the value.");
} else {
System.out.println("found the value.");
}
}
// Here's the search method used to pass the array and the scanner 
// input into it
public static int thisMethod(int[] array, int value) {
int middle;
int first = 0;
int last = array.length - 1;
int position = -1;
boolean found = false;
while (!found && first < = last) {
middle = (first + last) / 2;
if (array[middle] == value) {
found = true;
position = middle;
} else if (array[middle] > value) {
last = middle - 1;
} else {
first = middle + 1;
}
}
return position;
}
}

正如我们所知,对于二进制搜索实现,我们需要一个排序数组。所以您需要首先使用以下代码片段对数组进行排序

private static void sortArray(int[] array){
int temp;
for (int i = 1; i < array.length; i++) {
for (int j = i; j > 0; j--) {
if (array[j] < array [j - 1]) {
temp = array[j];
array[j] = array[j - 1];
array[j - 1] = temp;
}
}
}

在调用二进制搜索方法之前调用此方法,如下所示

sortArray(numbers);
foundValue = searchMethod(numbers,searchValue );

你会得到确切的答案。快乐编码:(

正如人们提到的,您需要首先对其进行排序。这段代码应该可以工作,不要忘记顶部的import语句。

import java.util.Arrays; 
public class chapter7Assignment{

public static void main(String[] args){

Scanner scanner = new Scanner(System.in);

int[] numbers = {1,566,18,1,8,5,18,4,3,8};
int searchValue;
int foundValue;

System.out.print("Enter a value: ");
searchValue = scanner.nextInt();
// Sort in ascending order
Arrays.sort(numbers);

foundValue = searchMethod(numbers,searchValue );

if(value == -1){
System.out.println("Didn't find the value.");
}else{
System.out.println("found the value.");
}
}

// Here's the search method used to pass the array and the scanner 
// input into it
public static int thisMethod (int [] array, int value){
int middle;
int first= 0;
int last = array.length -1;
int position = -1;
boolean found = false;


while(!found && first <= last){


middle = (first + last) / 2;
if(array[middle] == value){
found = true;
position = middle;
}
else if(array[middle] > value){
last = middle -1;
}else{
first = middle + 1;
}

}     

return position;       
}
}
}

最新更新