2

另外,为什么这会给我一个错误,因为我使用了 bool?

我需要使用这种顺序搜索算法,但我不确定如何使用。我需要将它与数组一起使用。有人可以指出我正确的方向或如何使用它。

bool seqSearch (int list[], int last, int target, int* locn){
     int looker;

     looker = 0;
     while(looker < last && target != list[looker]){
                  looker++;
     }

     *locn = looker;
     return(target == list[looker]);
}
4

4 回答 4

1

有几个问题。

  1. 我会将last的名称更改为size。
  2. 如果找不到该值,您将取消引用无效的内存位置。

编辑:我猜最后是length - 1. 这是一个不寻常的签名。所以调用是这样的:

int list[CONSTANT];
...
int foundIndex;
bool found = seqSearch(list, sizeof(list)/sizeof(int), target, &foundIndex);

有很多方法可以启用 bool。一是stdbool.h配合C99使用。

于 2010-05-04T06:19:42.003 回答
1

很清楚

list[]是您正在搜索的列表 last是最后一个索引list target是您正在搜索的list locn 内容将包含target找到的索引返回值是一个布尔值,指示是否target找到

对于您的问题如何通过 locn,请执行以下操作

int locn; /* the locn where the index of target will be stored if found */

bool target_found = seqSearch(blah blah blah, &locn);
于 2010-05-04T06:22:01.730 回答
1

您的代码的问题是,如果您搜索数组中不存在的元素,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.
}
于 2010-05-04T06:22:26.187 回答
1

看起来你会这样使用它......

// I assume you've set an int list[], an int listlen and an int intToFind

int where;
bool found = seqSearch(list, listlen - 1, intToFind, &where);
if (found)
{
    // list[where] is the entry that was found; do something with it
}
于 2010-05-04T06:27:07.367 回答