我正在研究二进制搜索算法以准备进行编码采访,但是我的算法仅适用于最佳情况,即,当搜索的数据位于中点O(1)时。当我将值更改为更差的情况(例如第一个位置)时,光标会卡住。我知道二进制搜索的情况更糟为O(log n),因此它不需要很长时间。我做错了吗?我正在使用C编程语言。
#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);
}
您通过从函数中未正确返回来触发无限递归。