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
|
#include <iostream>
using namespace std;
//Function prototypes:
int linearSearch(int [], int, int);
int binarySearch(int [], int, int);
int main()
{
const int SIZE=20;
int array[SIZE]={1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20};
int target=0, linearCount=0, binaryCount=0;
cout << "The numbers in the array in asending order: " << endl;
for(int x=0; x<SIZE; x++)
{
cout << array[x] << " ";
}
cout << endl;
cout << "Please enter the value to locate: ";
cin >> target;
linearCount=linearSearch(array, SIZE, target);
while(linearCount==-1)
{
cout << "The value you are looking for is not in the array." << endl;
cout << "Please enter another value from the list: ";
cin >> target;
linearCount=linearSearch(array, SIZE, target);//Function call;
}
cout << "The number of comparisons which the linear search made to find the value " << target << " is: " << linearCount+1 << endl;
binaryCount=binarySearch(array, SIZE, target);
cout << "The number of comparisons which the binary search made to find the value " << target << " is: " << binaryCount << endl;
return 0;
}
int linearSearch(int array[], int size, int value)
{
int index=0; //Used as a subscript to search array
int position=-1; //Used to record position of search value
bool found=false; //Flag to indicate if the value was found
while(index<size && !found)
{
if(array[index]==value)
{
found=true;
position=index;
}
index++;
return position;
}
}
int binarySearch(int array[], int size, int value)
{
int first=0,
last=size-1,
middle,
position=-1,
count=0;
bool found=false;
while(!found && first<=last)
{
if(position==-1)
{
count++;
}
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 count;
}
|