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 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125
|
#include <iostream>
using namespace std;
int binarySearch(const int array[], int numElems, int value);
int linearSearch(const int list[], int numElems, int value);
void showArray(const int [], int);
void sortArray(int[], int);
int main()
{
const int SIZE = 50;
int numbers[SIZE] = { 888, 552, 642, 191, 935, 584, 959, 495, 945, 27,
240, 637, 712, 608, 924, 630, 712, 234, 275, 258,
918, 15, 320, 144, 365, 305, 696, 783, 114, 434,
925, 462, 266, 985, 318, 728, 285, 79, 337, 115,
662, 798, 970, 433, 758, 213, 284, 154, 126, 543 };
int result;
cout << "Here are the numbers in the array: \n";
showArray(numbers, SIZE);
cout << "Please choose one of the numbers in the list " << endl;
cin >> result;
//linear Search
int count = linearSearch(numbers, SIZE, result);
if (count != -1)
{
cout << "The amount of comparison's used to find the number with linear search is " << count << endl;
}
else
cout << "Sorry, that number is not in the array" << endl;
sortArray(numbers, SIZE);
//binary Search
count = binarySearch(numbers, SIZE, result);
if (count != -1)
{
cout << "When sorted the amount of comparison's used to find the number with binary search is" << count << endl;
}
else cout << "Sorry, that number is not in the array" << endl;
system("pause");
return 0;
}
int linearSearch(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 index;
}
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;
}
void sortArray(int array[], int size)
{
bool swap;
int temp;
do
{
swap = false;
for (int count = 0; count < (size - 1); count++)
{
if (array[count] > array[count + 1])
{
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
swap = true;
}
}
} while (swap);
}
void showArray(const int array[], int size)
{
for (int count = 0; count < size; count++)
cout << array[count] << " ";
cout << endl;
}
|