问题描述
我实施在C ++中的二进制搜索算法,但算法没有返回正确的值。在code可以发现这里。
模板<类T>
INT binary_search的(T search_value,T search_array []){
INT中旬; / *要搜索的其余阵列的中间元件。 * /
INT分钟= 0; / *阵列的第一索引。 * /
/ *这forumla给我们的阵列的大小。 * /
INT最大= sizeof的(search_array)/的sizeof(search_array [0]);
/ *继续搜索,直到分钟> =最大值。 * /
而(分钟<最大){
/ *使用,不会产生许多一式计算中间值
*不是整数的最大允许值大。 * /
中期=(最大值 - 最小值)/ 2 +分钟;
/ *根据search_value是否比更大或更小
*的无论是search_array [MID]值,设置中间和最大的一个
*等于中旬。 * /
如果(search_value> search_array [MID])
分=中间+ 1;
否则,如果(search_value< search_array [MID])
最大=中等+ 1;
其他 {
返回中旬;
}
}
返回-1;
}
鉴于数组{0,1,3,5,7,9}和搜索3,函数应返回2,阵列中的3索引。我的函数返回-1,虽然,这意味着3并没有在数组中找到。哪里的问题?
INT最大= sizeof的(search_array)/ sizeof的(search_array [0]);
这个方法不好计算数组的大小,它只能在创建阵列功能。
通过你的数组的大小作为函数的参数,这是最简单的方法。
I'm implementing the binary search algorithm in C++, but the algorithm isn't returning the correct value. The code can be found here.
template<class T>
int binary_search(T search_value, T search_array[]) {
int mid; /* The middle element of the remaining array to be searched. */
int min = 0; /* The first index of the array. */
/* This forumla gives us the size of the array. */
int max = sizeof(search_array)/sizeof(search_array[0]);
/* Continue searching until min >= max. */
while (min < max) {
/* Compute the value of mid using a formula that won't produce a number
* larger than the maximum allowed value of an integer. */
mid = (max-min)/2 + min;
/* Depending the whether search_value is larger or smaller than the
* value of whatever is at search_array[mid], set one of mid and max
* equal to mid. */
if (search_value > search_array[mid])
min = mid + 1;
else if (search_value < search_array[mid])
max = mid + 1;
else {
return mid;
}
}
return -1;
}
Given an array {0, 1, 3, 5, 7, 9} and searching for 3, the function should return 2, the index of 3 in the array. My function is returning -1 though, which means 3 was not found in the array. Where's the problem?
int max = sizeof(search_array)/sizeof(search_array[0]);
This approach is not good to compute the size of the array, it works only in the function where you create your array.
Pass the size of your array as a parameter of your function, it's the easiest approach.
这篇关于二进制搜索没有返回正确的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!