2017-08-11 55 views
-1

我已經在C語言中實現了二進制搜索的初始遞歸版本。但是,當要找到的元素位於數組的最後位置時,它似乎不起作用。有沒有辦法解決這個問題,而不改變函數的原型?爲什麼我的二進制搜索實現不能找到最後一個元素?

#include <stdio.h> 

int search(int value, int values[], int n); 

int main() { 
    int a[] = { 26, 27, 28 }; 

    if (search(28, a, 3) == 0) 
     printf("Found.\n"); 
    else 
     printf("Not found.\n"); 
} 

int search(int value, int values[], int n) 
{ 
    if (n <= 0) 
     return 1; 

    if (value < values[n/2]) 
     // Search the left half 
     return search(value, values, n/2); 
    else if (value > values[n/2]) 
     // Search the right half, excluding the middle term 
     return search(value, values + n/2 + 1, n/2 - 1); 
    else 
     return 0; 

    return 1; 
} 
+0

我只是跑你的代碼;它工作正常嗎?你能澄清你的錯誤,你可重複的步驟? – Miket25

+0

爲什麼如果'value == values [n/2]'返回'0'?你不應該返回'n/2'嗎?而'return 1'這一行沒用。 –

+0

@EugeneSh。我認爲零是正確的,它返回0或1來表示是否找到一個值,0是正確的。 – Miket25

回答

2

search功能是不正確的:

  • 當你遞歸右側部分傳遞片尺寸的計算錯誤:它應該是n - n/2 - 1而不是n/2 - 1

這裏是一個修正版本:

#include <stdio.h> 

int search(int value, int values[], int n); 

int main(void) { 
    int a[] = { 26, 27, 28 }; 

    if (search(28, a, 3) == 0) 
     printf("Found.\n"); 
    else 
     printf("Not found.\n"); 

    return 0; 
} 

int search(int value, int values[], int n) { 
    if (n > 0) { 
     int mid = n/2; 
     if (value < values[mid]) { 
      // Search the left half 
      return search(value, values, mid); 
     } else 
     if (value > values[mid]) { 
      // Search the right half, excluding the middle term 
      return search(value, values + mid + 1, n - mid - 1); 
     } else { 
      // Found the value 
      return 0; 
     } 
    } 
    return 1; 
} 

下面是一個簡單的迭代版本:

int search(int value, int values[], int n) { 
    while (n > 0) { 
     int mid = n/2; 
     if (value < values[mid]) { 
      // Search the left half 
      n = mid; 
     } else 
     if (value > values[mid]) { 
      // Search the right half, excluding the middle term 
      values += mid + 1; 
      n -= mid + 1; 
     } else { 
      // Found the value 
      return 0; 
     } 
    } 
    return 1; 
} 
0

它似乎是你的else if語句中的返回語句。數組n的長度應該是n-n/2-1而不是n/2-1否則最後一個元素將被刪除。隨着數組長度的增加以及您搜索來自右側的元素,您可以看到這種情況更爲普遍。

return search(value, values + n/2 + 1, n - n/2 - 1); 

注: 作爲chqrlie指出

+0

@chqrlie這就是好點和重要的一點。雖然我會把它留給OP的判斷,因爲主要關心似乎是數學邏輯。 – Miket25

+0

@chqrlie事實上,這將解決出界問題,很好的抓住。 – Miket25

相關問題