尝试学习一些基本的数据结构和算法,我尝试编写基本的二分搜索代码,但除非输入与中间相同,否则它不起作用?有人可以帮忙吗?
void Search(int input) {
int array[10] = { 0.1,2,3,4,5,6,7,8,9,10 };
int first = array[0];
int last = sizeof(array) / sizeof(array[0]);;
int middle = first + last / 2;
if (input == middle) {
cout << "search succesful";
}
else if (input > middle) {
middle + 1;
Search(input);
}
else if (input < middle) {
middle - 1;
Search(input);
}
}
int main()
{
int input;
cin >> input;
Search(input);
}
Run Code Online (Sandbox Code Playgroud)
小智 5
如果您想使用递归,那么您还应该传递数组的左右边框并在 if 语句中更改它们。当你这样做时,middle-1
你不会改变任何东西。这是二分查找的实现
int binarySearch(int nums[], int low, int high, int target)
{
// Base condition (search space is exhausted)
if (low > high) {
return -1;
}
// find the mid-value in the search space and
// compares it with the target
int mid = (low + high)/2; // overflow can happen
// int mid = low + (high - low)/2;
// Base condition (target value is found)
if (target == nums[mid]) {
return mid;
}
// discard all elements in the right search space,
// including the middle element
else if (target < nums[mid]) {
return binarySearch(nums, low, mid - 1, target);
}
// discard all elements in the left search space,
// including the middle element
else {
return binarySearch(nums, mid + 1, high, target);
}
}
Run Code Online (Sandbox Code Playgroud)