2010-07-18 64 views
0
import java.io.*; 
import java.lang.Integer; 

class sort { 
    public void find(int val, int a[], int n) { 
     int mid = n/2; 
     System.out.println("the mid value is:" + a[mid]); 
     if (a[mid] == val) { 
      System.out.println("found " + a[mid] + " in position " + mid); 
     } else if (a[mid] < val) { 
      for (int i = mid; i < n; i++) { 
       if (a[mid] == val) { 
        System.out.println("found" + val); 
       } 
      } 
     } else if (a[mid] > val) { 
      for (int i =0; i < mid; i++) { 
       if (a[mid] == val) { 
        System.out.println("found" + val); 
       } 
      } 
     } 
    } 


    public static void main(String args[])throws IOException { 
     DataInputStream in = new DataInputStream(System.in); 
     int temp; 
     int a[] = new int[100]; 
     System.out.println("enter the nos of elements"); 
     int n = Integer.parseInt(in.readLine()); 
     for (int i =0; i < n; i++) { 
      a[i] = Integer.parseInt(in.readLine()); 
     } 
     for (int i =0; i < n; i++) { 
      for (int j = i + 1; j < n; j++) { 
       if (a[i] > a[j]) { 
        temp = a[i]; 
        a[i] = a[j]; 
        a[j] = temp; 
       } 
      } 
     } 
     for (int i =0; i < n; i++) { 
      System.out.println(a[i]); 
     } 

     System.out.println("enter the value to be searched"); 
     int val = Integer.parseInt(in.readLine()); 
     sort s = new sort(); 
     s.find(val, a, n); 
    } 
} 

通過上面的代碼,我想從現有數組列表中使用二分查找來查找用戶定義的值。它只檢查中間值,而不檢查更高或更低的值。實現二進制搜索

我認爲循環無法正常工作。

請爲此找到解決方案。

+0

這不是二進制搜索。 – 2010-07-18 05:45:10

+0

@True Soft,部分是二分查找,但是,這不是二分查找。我不確定@mano是否已準備好遞歸。 – strager 2010-07-18 05:46:52

回答

4

你的兩個內環:

for(int i=mid;i<n;i++) 
    { 
    if (a[mid] ==val) 
    System.out.println("found"+val); 
} 



    for(int i=0;i<mid;i++) 
{ 
if ( a[mid] ==val) 
    System.out.println("found"+val); 
    } 

請注意,您正在訪問a[mid]mid在整個循環中不會改變;你打算使用a[i]。嘗試用i替換mid

此外,你可能想看看縮進你的代碼。你用什麼編輯器編寫你的代碼?

0

修改您的發現()函數如下遞歸地找到下搜索值實際能夠稱爲二進制搜索 -

public void find(int val, int a[], int startIndex, int endIndex) { 
    if(endIndex-startIndex == 1) { 
     System.out.println("Not found"); 
     return; 
    } 
    int mid = startIndex + ((endIndex-startIndex)/2); 
    System.out.println("the mid value is:" + a[mid]); 
    if (a[mid] == val) { 
     System.out.println("found " + a[mid] + " in position " + mid); 
    } else { 
     if(a[mid] > val) { 
     find(val, a, startIndex, mid); 
     } else { 
     find(val, a, mid, endIndex); 
     } 
    } 
    } 

您可以用的startIndex零和endIndex調用功能爲長度數組減1。

0

我可以建議在再次調用這些位置定義的分區上的搜索之前檢查極端位置值嗎?