1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
|
// Search Benchmarks
#include <iostream>
using namespace std;
// Global Constants
const int ARRAY_SIZE = 20; // The array size
// Function prototype
int linearSearchBench(int [], int, int);
int binarySearchBench(int [], int, int);
int searchFor = 521; // declared and assigned value to be searched for
int main()
{
int comparisons; // To hold the number of comparisons.
// Initialize an array with 20 integer values.
int tests[ARRAY_SIZE] = { 101, 142, 147, 189, 199, 207, 222,
234, 289, 296, 310, 319, 388, 394,
417, 429, 447, 521, 536, 600 };
// Display the value being searched for.
cout << "Searching for the value 521 ";
// Perform the linear search.
comparisons = linearSearchBench(tests, ARRAY_SIZE, searchFor);
// Display the results of the linear search.
cout << "The linear search made " << comparisons;
cout << " comparisons.\n";
// Perform the binary search.
comparisons = binarySearchBench(tests, ARRAY_SIZE, searchFor);
// Display the results of the binary search.
cout << "The binary search made " << comparisons;
cout << " comparisons.\n";
return 0;
}
// user defined functions
int linearSearchBench(const int testsLin[], int numElem, int searchValue) { // created the linearSearchBench function to do a linear search of the array
int i; // initialized the counter variable
for (i = 0; i < numElem; i++) // for loop to loop through array
if (testsLin[i] == searchValue)
return i;
return -1;
}
int binarySearchBench(const int testsBin[], int numElems, int searchValue) { // created the binSearch function to do a binary search of the array
int first = 0;
int last = numElems -1;
int middle = 0;
int position = -1;
bool found = false;
while (!found && first <= last) {
middle = (first + last) / 2;
if (testsBin[middle] == searchValue) {
found = true;
position = middle;
}
else if (testsBin[middle] > searchValue)
last = middle -1;
else first = middle + 1;
}
return position;
}
|