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 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96
|
#include <iostream>
using namespace std;
int searchList(const int list[], int numElems, int value);
int binarySearch(const int array[], int numElems, int value);
int main ()
{
const int arraySize = 20;
int a[arraySize] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int number;
int count = 0;
cout << "Please pick a number between 1 and 20 to search the index for." << endl;
cin >> number;
//Linear Search
int index = searchList(a, arraySize, number);
if(index !=-1)
{
cout << "The number's element found by linear search is " << index << endl;
count++;
cout << "The amount of comparison's used to find the element\nWith linear search is " << count << endl;
}
else
cout << "That is not a valid number within the linear search index" << endl;
//Binary Search
index = binarySearch(a, arraySize, number);
if(index != -1)
{
cout << "The number's element found by binary search is " << index << endl;
count++;
cout << "The amount of comparison's used to find the element\nWith binary search is " << count << endl;
}
else
cout << "That is not a valid number within the binary search index." << endl;
return 0;
}
//Linear Search Function
int searchList(const int list[], int numElems, int value)
{
int index = 0;
int position = -1;
bool found = false;
while (index < numElems && !found)
{
if (list[index] == value)
{
found = true;
position = index;
}
index++;
}
return position;
}
//Binary Search Function
int binarySearch(const int array[], int size, int value)
{
int first = 0,
last = size - 1,
middle,
position = -1;
bool found = false;
while (!found && first <= last)
{
middle = (first + last) / 2;
if (array[middle] == value)
{
found = true;
position = middle;
}
else if (array[middle] > value)
last = middle - 1;
else
first = middle + 1;
}
return position;
}
| |