我需要帮助我的代码。我希望它在每次分割时显示数组,同时包含键值,直到它到达时带有键值的最简单数组,然后显示"找到!"。我的问题是,它仅适用于key = 2而不适用于其他键。请帮助我。
package Search;
import java.util.*;
public class BinarySearch{
/**Example is below of what I expected which is a result I obtained from key = 2
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
[1, 2, 3, 4, 5, 6]
[1, 2]
Found!
**/
public static int binarySearch(int[] list, int key){
int low = 0;
int high = list.length;
while(high >= low){
int mid = (low+high)/2;
int[] temp = new int[high];
System.arraycopy(list, low, temp, 0, high);
System.out.println(Arrays.toString(temp));
int count = 0;
if(key < list[mid]){
high = mid - 1;
if(count<temp.length){
}
}
else if(key == list[mid]){
return mid;
}
else{
low = mid + 1;
}
}
return -1;
}
public static int User(){
Scanner scan = new Scanner(System.in);
System.out.println("Enter key: ");
String input = scan.nextLine();
int user = Integer.parseInt(input);
return user;
}
public static void main(String[] args){
int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
System.out.println("The array: "+Arrays.toString(list));
System.out.println("The key is found at "+BinarySearch.binarySearch(list, BinarySearch.User()));
}
}