Purchase Solution

Add a counter to sequential and binary search

Not what you're looking for?

Ask Custom Question

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

Purchase this Solution

Solution Summary

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

Purchase this Solution


Free BrainMass Quizzes
Java loops

This quiz checks your knowledge of for and while loops in Java. For and while loops are essential building blocks for all Java programs. Having a solid understanding of these constructs is critical for success in programming Java.

Javscript Basics

Quiz on basics of javascript programming language.

Excel Introductory Quiz

This quiz tests your knowledge of basics of MS-Excel.

Word 2010: Tables

Have you never worked with Tables in Word 2010? Maybe it has been a while since you have used a Table in Word and you need to brush up on your skills. Several keywords and popular options are discussed as you go through this quiz.

Word 2010: Table of Contents

Ever wondered where a Table of Contents in a Word document comes from? Maybe you need a refresher on the topic? This quiz will remind you of the keywords and options used when working with a T.O.C. in Word 2010.