Share
Explore BrainMass

Add a counter to sequential and binary search

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

Solution Summary

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

$2.19