2013-04-26 70 views
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; 
    } 
} 
+1

你只能搜索[低;高]即在索引0 – RiaD 2013-04-26 20:24:18

+0

@RiaD那麼這種看起來像一個任務,所以我想他們必須實現自己的。 – 2013-04-26 20:27:02

+0

@HunterMcMillen,我明白了。但是我發現重要的是要提醒有一種標準的方式,當OP在他的真實代碼中使用它時應該考慮使用它 – RiaD 2013-04-26 20:29:36

回答

1

我覺得high變量不等於0,則需要該數組像這樣的長度:

int high = array.length-1; 
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

你永遠不會初始化high它搜索0 0之間