我正在C++中實現二進制搜索算法,但算法沒有返回正確的值。代碼可以找到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;
}
鑑於數組{0,1,3,5,7,9}和搜索3,函數應返回2,3陣列中的索引。我的函數返回-1,這意味着3在數組中找不到。問題在哪裏?
開始似乎是一個非常瑣碎測試用例在調試器到步驟通過.. – Blorgbeard 2012-02-13 21:59:03
第一。在函數中使用sizeof-construction來接收數組大小是一個壞主意。在函數中再加一個參數,比如'int array_size' – mikithskegg 2012-02-13 22:00:57
你試過調試嗎? – littleadv 2012-02-13 22:01:27