2016-10-20 67 views
2

運行到一個愚蠢的錯誤,我只是沒有看到它。我一直在看這一段時間,並沒有看到我錯過了什麼。我遞歸搜索一個數組的特定目標編號,但一旦我到達元素[7]它開始返回-1。謝謝你看看傢伙/女士們!遞歸搜索錯誤

public static void main(String[] args) 
    { 
     int[] a = {1,25,2,6,4,3,23,30,32,14,11,8}; 
     Arrays.sort(a); 
     int target = a[7]; 
     int first = a[0]; 
     int last = a.length; 
     for(int i=0;i<a.length;i++) 
     { 
      System.out.print(" "+a[i]); 
    } 
     System.out.println("\n"+binarySearch(target,first,last,a)); 
    } 
    public static int binarySearch(int target,int first, int last, int[] a) 
    { 
     int result; 
     if(first>last) 
      return -1; 
     else 
     { 
      int mid = (first+last)/2; 
      if(target == mid) 
       result = mid; 
      else if(target<a[mid]) 
       result = binarySearch(target,first,last-1,a); 
      else 
       result = binarySearch(target,mid+1,last,a); 

     } 
     return result; 
    } 
+0

具體而言,當你計算的中期,你打算計算中間是中等折射。所以你不能使用像這樣的值:'(first + last)/ 2'。你需要索引。對?想想......你會到達的! – code4kix

回答

2

在幾個地方,您無法準確區分數組索引中的值和索引本身。

此:a[i]在第i個元素

這得到值:i是一個簡單的指標,我

考慮到這一點,這裏是你的代碼的固定版本。看到我的代碼中的註釋爲我修正了一些具體錯誤:

public static void main(String[] args) 
{ 
    int[] a = {1,25,2,6,4,3,23,30,32,14,11,8}; 
    Arrays.sort(a); 
    int target = a[7]; 
//here you want the index of the first location to search, not the value in that index 
//so you use 0 instead of a[0] 
    int first = 0; 
//the last element index is length-1, not length, since arrays are 0-based 
    int last = a.length - 1;  
    for(int i=0;i<a.length;i++) 
    { 
     System.out.print(" "+a[i]); 
    } 
    System.out.println("\n"+binarySearch(target,first,last,a)); 
} 

public static int binarySearch(int target,int first, int last, int[] a) 
{ 
    int result; 
    if(first>last) 
     return -1; 
    else 
    { 
     int mid = (first+last)/2; 
//here you need to check if the target is equal to the value at the index mid 
//before you were checking if the target was equal to the index, which was never true 
     if(target == a[mid]) 
//you want to return the value at the target, not the index of the target 
//so use a[mid] not mid 
      result = a[mid]; 
     else if(target<a[mid]) 
//here you want to search from first to mid-1 
//before you were searching from first to last-1, which is not correct binary search 
      result = binarySearch(target,first,mid - 1,a); 
     else 
      result = binarySearch(target,mid + 1,last,a); 

    } 
    return result; 
} 
+0

我試過這..這不起作用,它只是給我的目標作爲一個int目標,而不是作爲目標的指數 –

+0

我的意思是我有這個想法的分鐘之前,你的回答,但仍然不正確。 –

+0

@JaredWaxler我正在運行它,它返回7,它是目標的索引。如果你說它輸出了不同的東西,請解釋它爲你輸出的內容。 – nhouser9