![](/img/trans.png)
[英]What am I doing wrong in my C binary search code? (iterative & recursive)
[英]What am I doing wrong in my C binary search code?
我正在研究二進制搜索算法以准備我的編碼面試,但是我的算法僅適用於最佳情況,即當搜索的數據處於中點時,O(1)。 當我將值更改為更糟糕的情況時,cursor 卡住了,比如第一個 position。
我知道二進制搜索有一個 O(log n) 更壞的情況,所以它不應該花很長時間。 我做錯了嗎?
#include <stdio.h>
int binary_search(int arr[], int left, int right, int data){
// condition that runs only if true
while(left <= right){
int mid = (left + right) / 2;
if(data == arr[mid]){
return mid;
}
if(data > arr[mid]){
binary_search(arr, mid+1, right, data);
}
binary_search(arr, left, mid-1, data);
}
return -1;
}
void main(){
int arr[] = {1,2,3,4,5,6,7,8,9};
int result = binary_search(arr, 0, (sizeof(arr)/sizeof(arr[0]) - 1), 2);
(result == -1) ? printf("There was no record found\n") : printf("Your record was found at position %d\n", result+1);
}
您沒有從 function 正確返回,從而觸發了無限遞歸。 您在哪里調用binary_search(arr, mid+1, right, data);
遞歸地,您需要將返回值傳播回調用 function。
此外,與您的問題無關,但在 C 中, void main()
在技術上是不合法的,即使您可能沒有得到任何明確的錯誤。 main() 應該總是返回一個 int。
#include <stdio.h>
int binary_search(int arr[], int left, int right, int data){
// condition that runs only if true
while(left <= right){
int mid = (left + right) / 2;
if(data == arr[mid]){
return mid;
}
if(data > arr[mid]){
return binary_search(arr, mid+1, right, data);
}
return binary_search(arr, left, mid-1, data);
}
return -1;
}
int main(void){
int arr[] = {1,2,3,4,5,6,7,8,9};
int result = binary_search(arr, 0, (sizeof(arr)/sizeof(arr[0]) - 1), 2);
(result == -1) ? printf("There was no record found\n") : printf("Your record was found at position %d\n", result+1);
return 0;
}
您的代碼不起作用,因為如果在第一次迭代中data
不等於arr[mid]
,您的遞歸 function 不會返回任何內容。 因此,在這種情況下,您將進行無限遞歸。
但無論如何,對於專業程序員來說,代碼非常非常弱。
例如,您的 function 可能不會為常量數組調用。 (是否需要另外一個名稱不同的 function?)
function應該只有三個參數
return_type binary_search( const int a[], size_t n, int data );
如果 function 返回目標元素的索引,則其返回類型應為size_t
,因為通常類型int
無法容納表達式sizeof( a ) / sizeof( *a )
的值。
如果 function 僅檢查給定值是否存在於數組中,則它應返回0
或1
並且其返回類型應為int
或_Bool
。
If the function should return a position of the target value then it should return the first position of the element with the target value the same way as the standard algorithm std::lower_bound in C++ does.
復制標准 C function bsearch
的相同缺點不是一個好主意,通常也不返回具有目標值的第一個元素的 position。
您不應使用運算符 == 來比較值(盡管 C 中的比較函數使用此運算符),因為例如對於浮點數,您可能會得到錯誤的結果。 您應該只使用運算符 <。
好吧,讓我們假設您的 function 適用於元素類型int
和運算符 < 的 arrays。 但是如果用戶想對數組元素使用自己的比較function怎么辦?
第二個問題,如果用戶要使用元素類型為long long
的數組或結構數組,他是否需要花時間再編寫一個二進制搜索 function?
我的建議:永遠不要在面試中做任何作業。 忽略那些試圖操縱你和你的時間的公司。 面試是平等伙伴的對話。 只要您自己是一名合格的程序員,在簡單的對話中就很容易理解“誰是誰”。 :)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.