Counting comparisons in a linear search

In this linear search the purpose is to compare the values of the elements in two arrays and then count up the number of comparisons it took for the search to complete. The Array objects have built in arrays within them as well as overloaded operators and numComparison functions. The problem I am getting is that it keeps outputting the number 5000 for numComparisons, which is the maximum amount of comparisons possible, which will happen pretty much never. SearchArr contains five random numbers between 0-999, while arr contains the numbers 0 through 999, so, for example if element 0 of searchArr was 15, when checking against arr it should only take 16 iterations and thus 16 comparisons. There must be something wrong with my loop but I can't figure it out, thank you for any help.

1
2
3
4
5
6
7
8
9
10
11
  bool linearSearch(Array arr, Array searchArr, int n, int x) {
   bool flag=false;
   for (int z=0; z<x;z++) {
        for (int i = 0; i < n; i++){
            if (searchArr[z] == arr[i]) {
                flag=true;
                }
        }
   }
   return flag;
}
Last edited on
You would probably want to break out of both loops once flag is set to true?

Otherwise would need more info about your overloaded operators etc.
thanks, yeah that's what I ended up figuring out . just needed a well placed break.
Topic archived. No new replies allowed.