Computer Science Homework Solutions
Problem
#153984

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
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
What is this?
By OTA - Overall OTA Rating
Yanfang Li, PhD - 4.9/5
Purchase Cost Now
$2.19 CAD (was ~$11.97)
Included in Download
  • Plain text response
  • Attached file(s):
    • test.cpp
$2.19 Instant Download
Add to Cart
Why you can trust BrainMass.com
  • Your Information is Secure
  • Best Online Academic Help Service
  • Students find real academic Success
Related Solutions
Browse