Problem with sequential search algorithm

Also why is it giving me an error because I used bool?

I need to use this sequential search algorithm, but I'm not really sure how to do it. I need to use it with an array. Can someone point me in the right direction or something like that.

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]);
}

      

+2


a source to share


4 answers


It looks like you would use it like this ...



// 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
}

      

+1


a source


There are several problems.

  • I would change the name of the latter to size.
  • If you don’t find the value, you’ll find the wrong memory location.

EDIT: I think the latter is this length - 1

. This is an unusual signature. So the call looks something like this:



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

      

There are many ways to enable bool. One of them is for use stdbool.h

with C99.

+1


a source


It's pretty clear

list[]

- the list you are looking for last

- the last index in list

target

is what you are looking for in list

locn

will contain the index in which the target

return value was found is boolean if specifiedtarget

for your question, how to pass locn, do something like

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

bool target_found = seqSearch(blah blah blah, &locn);

      

+1


a source


The problem with your code is finding an element that is not in the array looker

will be equal last

and you will try to access an element of the array at a location last

that is invalid.

Instead, you can:

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.
}

      

You call the function like this:

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.
}

      

+1


a source







All Articles