代码之家  ›  专栏  ›  技术社区  ›  shinjuo

顺序搜索算法的问题

  •  2
  • shinjuo  · 技术社区  · 15 年前

    为什么这会给我一个错误,因为我用了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 回复  |  直到 15 年前
        1
  •  1
  •   cHao    15 年前

    看来你会用这个…

    // 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
    }
    
        2
  •  1
  •   hhafez    15 年前

    很清楚

    list[] 是您正在搜索的列表 last list target 是你在找的东西 列表 locn 将包含 目标 被发现 返回值是一个布尔值,指示 目标 被发现

    对于你的问题,如何通过locn,做一些像

    int locn; /* the locn where the index of target will be stored if found */
    
    bool target_found = seqSearch(blah blah blah, &locn);
    
        3
  •  1
  •   codaddict    15 年前

    代码的问题是如果搜索数组中不存在的元素, looker 将等于 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.
    }
    
        4
  •  1
  •   Matthew Flaschen    15 年前

    有几个问题。

    1. 我会把姓氏改成大小。
    2. 如果找不到该值,则会取消对无效内存位置的引用。

    编辑:我想最后一个是 length - 1 . 那是个不寻常的签名。所以电话是这样的:

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

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