2013-10-10 99 views
0

這是我的二分查找程序:Java的二進制搜索錯誤

import java.io.*; 
    public class Program14 
{ 
public void ArraySearching()throws IOException 
{ BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
    int A[]=new int[15]; 
    System.out.println("Input an array of 15 elements in descending order"); 
    for(int i=0;i<15;i++) 
    { 
     int j=Integer.parseInt(br.readLine()); 
     j=A[i]; 
    } 
    System.out.println("Input the number to be searched"); 
    int n=Integer.parseInt(br.readLine()); 
    System.out.println("Press 1 for Binary search"); 
    System.out.println("Press 2 for linear search"); 
    int ch=Integer.parseInt(br.readLine()); 
    switch(ch) 
    { 
     case 1: 
    { 
     int flag=0,low,up,mid=0; 
     low=0; 
     up=14; 
     while(low<=up) 
     { 
      mid=(low+up)/2; 
      if(n>A[mid]) 
      low=mid+1; 
      else if(n<A[mid]) 
      up=mid-1; 
      else 
      {flag=1; 
       break; 
      } 
     } 
     if(flag==1) 
     System.out.println("Element at position"+(mid+1)); 
     else 
     System.out.println("Element not found"); 
     break; 
    } 
}}} 

輸出始終「找不到元素」。有人能指出我的錯誤嗎?程序的線性搜索部分尚未完成。提前致謝。

回答

0
public static void main(String[] args) throws IOException 
    { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); 
    int A[]=new int[15]; 
    System.out.println("Input an array of 15 elements in descending order"); 
    for(int i=0;i<15;i++) 
    { 
     int j=Integer.parseInt(br.readLine()); 
     A[i]=j; 
    } 
    System.out.println("Input the number to be searched"); 
    int n=Integer.parseInt(br.readLine()); 
    System.out.println("Press 1 for Binary search"); 
    System.out.println("Press 2 for linear search"); 
    int ch=Integer.parseInt(br.readLine()); 


    switch(ch) 
    { 
    case 1: 
    { 
     int flag=0,low,up,mid=0; 
     low=0; 
     up=14; 
     int count = 0; 
     mid=(low+up)/2; 
     while(low<=up) 
     { 

      if(n>A[mid]){ 
           mid--; 
          } 
      else if(n<A[mid]){ 

       mid++; 
          } 
      else 
      { 

       flag=1; 
      break; 
      } 
      count++; 
     } 
     System.out.println(count); 
     if(flag==1) 
      System.out.println("Element at position"+(mid+1)); 
     else 
      System.out.println("Element not found"); 
     break; 
    } 
    } 
    } 
+0

這種解決方案是錯誤的。修改中間值(mid-或mid ++)實際上不執行二分搜索,它只是從一個值搜索到下一個值,直到找到答案。 – Jason

0

你行:

j=A[i]; 

應該是:

A[i]=j; 

此外,您還需要交換以下兩行的位置:

low = mid + 1; 
up = mid - 1; 
+0

我改變了它但它仍然說「找不到元素」 – aqua

+0

編輯我的答案讓它起作用。 – Jason