Explore BrainMass
Share

Explore BrainMass

    Add a counter to sequential and binary search

    This content was COPIED from BrainMass.com - View the original, and get the already-completed solution here!

    I have code for a sequential search and a binary search. I have to "add a counter for every key comparison in each search function and print out the number of key comparisons for each search."

    Here is my code:

    #include <iostream>
    using namespace std;

    int SequentialSearch(const int _list[], int _length, const int & _item);
    int BinarySearch(const int _list[], int _length, const int & _item);

    int main()
    {
    int temp;
    int numbers[] = {5,10,15,20,25,30,35,40,45,50};
    cout << SequentialSearch(numbers, 10, 30) << endl;
    cout << BinarySearch(numbers, 10, 30) << endl;

    cin >> temp;
    return 0;
    }
    int SequentialSearch(const int _list[], int _length, const int & _item)
    {
    for (int x = 0; x< _length; x++)
    {
    if (_list[x] == _item)
    return x;
    }
    return -1;
    }
    int BinarySearch(const int _list[], int _length, const int & _item)
    {
    int first = 0;
    int last = _length -1;
    int mid = 0;
    bool found = false;

    while (first <= last && !found)
    {
    mid = (first + last) / 2;
    if (_list[mid] == _item)
    found = true;
    else if (_list[mid] > _item)
    last = mid - 1;
    else
    first = mid + 1;
    }
    if (found)
    return mid;
    else
    return -1;
    }

    © BrainMass Inc. brainmass.com October 9, 2019, 8:31 pm ad1c9bdddf
    https://brainmass.com/computer-science/searching/counter-sequential-binary-search-153984

    Solution Summary

    It provides code to implement the following function: "Add a counter to sequential and binary search".

    $2.19