Question

Also why does this give me an error because I used bool?

I need to use this sequential search algorithm, but I am not really sure how. I need to use it with an array. Can someone point me in the correct direction or something on how to use this.

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]);
}
Was it helpful?

Solution

Looks like you'd 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
}

OTHER TIPS

It's pretty clear

list[] is the list you are searching last is the last index in the list target is what you are searching in list locn will contain the index at which target was found the return value is a boolean indicating if the target was found

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

The problem with your code is if you search for an element not present in the array, looker will be equal to last and you try to access an array element at location last which is invalid.

Instead you can do:

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 as follows:

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

There are a few issues.

  1. I would change the name of last to size.
  2. If you don't find the value, you will dereference an invalid memory location.

EDIT: I guess last is the length - 1. That's an unusual signature. So the call is something like:

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

There are many ways to enable bool. One is to use stdbool.h with C99.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top