您的代码的问题是,如果您搜索数组中不存在的元素,looker
将等于last
并且您尝试访问last
无效位置的数组元素。
相反,您可以这样做:
bool seqSearch (int list[], int last, int target, int* locn) {
int looker;
for(looker=0;looker<last;looker++) {
// target found.
if(list[looker] == target) {
*locn = looker; // copy location.
return true; // return true.
}
}
// target not found.
*locn = -1; // copy an invalid location.
return false; // return false.
}
您按如下方式调用该函数:
int list[] = {5,4,3,2,1}; // the array to search in.
int size = sizeof(list)/sizeof(list[0]); // number of elements in the array.
int target = 3; // the key to search for.
int locn; // to hold the location of the key found..and -1 if not found.
if( seqSearch(list,size,target,&locn) ) {
// target found in list at location locn.
} else {
// target not found in list.
}