Advertisement

counting iterations in linear search

Started by January 03, 2025 08:07 PM
2 comments, last by pbivens67 1 week, 6 days ago

I am attempting to count the iterations in a linear search

#include <iostream>

using namespace std;

int cnt = 0;

int searchList(int stdList[], int numElems, int value)
{
    int index = 0;
    int position = -1;
    bool found = false;

    while (index < numElems && !found)
    {
        cnt++;
        if (stdList[index] == value)
        {
            found = true;
            position = index;
        }
        index++;
    }
    cout << cnt << endl;
    return position;
}

int main() {
    int array[] = { 2, 4, 0, 1, 9 };
    int x = 1;
    int n = sizeof(array) / sizeof(array[0]);

    int result = searchList(array, n, x);

    (result == -1) ? cout << "Element not found" : cout << "Element found at index: " << result;
}

Potentially a good learning exercise for a student. Did you learn anything?

Advertisement

I am learning about searching and sorting

Advertisement