我创建了一个生成随机10数字数组的程序,使用冒泡排序对数组进行排序,然后使用二进制搜索来查看该值是否在数组中。我的所有代码对我来说都是正确的,但每次我运行程序时,如果我选择搜索的数字在数组中是不完整的,它仍然告诉我它不是。我相信它与我的返回值有关,但代码看起来对我来说正确。
import java.util.Scanner;
public class BubbleSort {
public static void main(String[] args) {
final int SIZE=10;
int[] numbers= new int[SIZE];
int number;
int result;
Scanner keyboard = new Scanner(System.in);
loadArray(numbers);
sortArray(numbers);
displayArray(numbers);
System.out.print("Enter your number: ");
number=keyboard.nextInt();
result=binarySearch(numbers, number);
if(result==-1){
System.out.print("Your number was not found");
}else{
System.out.print("Your number was found");
}
}
public static void loadArray(int[] numbers){
int index;
for(index=0;index<numbers.length;index++){
numbers[index]=(int)(Math.random()*100)+1;
}
}
public static void sortArray(int[] num){
int index;
int passNo;
int holdingnumber;
//boolean condition=true;
//while(condition){
//condition=false;
for(passNo=0;passNo<num.length-1;passNo++){
for(index=0;index<num.length-1;index++){
if(num[index]>num[index+1]){
holdingnumber=num[index+1];
num[index+1]=num[index];
num[index]=holdingnumber;
//condition=true;
}
}
}
}
public static void displayArray(int[] numbers){
int index;
for(index=0;index<numbers.length;index++){
System.out.println("Element["+index+"]: " +numbers[index]);
}
}
public static int binarySearch(int[] array, int number){
int low=0;
int mid=0;
int high=0;
while(low<=high){
mid=(low+high)/2;
if(array[mid]>number){
high=mid-1;
}else if(array[mid]<number){
low=mid+1;
}else{
return mid;
}
}
return -1;
}
}
答案 0 :(得分:1)
检查二进制搜索方法:
public static int binarySearch(int[] array, int number){
int low=0;
int mid=0;
int high=0;
while(low<=high){
mid=(low+high)/2;
if(array[mid]>number){
high=mid-1;
}else if(array[mid]<number){
low=mid+1;
}else{
return mid;
}
}
return -1;
}
您需要将高启动作为数组的最后一个索引。您的代码检查0到0之间的索引值。
答案 1 :(得分:1)
你从不初始化high
它在0和0之间搜索
答案 2 :(得分:1)
我认为high
变量不等于0,它需要是数组的长度像这样:
int high = array.length-1;