0

我创建了一个程序,它生成一个随机的 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;
    }
}
4

3 回答 3

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 之间的索引值。

于 2013-04-26T20:25:03.773 回答
1

你永远不会初始化high 它在 0 和 0 之间搜索

于 2013-04-26T20:25:11.953 回答
1

我认为high变量不等于 0 ,它需要是数组的长度 像这样:

  int high = array.length-1;
于 2013-04-26T20:27:29.000 回答