Imagine you have 101 dalmatians and that no two dalmatians have the same number of spots. Suppose that you create an array of 101 integers: the first integer is the number of spots on the first dalmatian, the second integer is the number of spots on the second dalmatian, and so on. Your friend wants to know whether you a dalmatian with 99 spots. Thus you need to determine whether your array contains the integer 99.
a. if you plan to use a binary search to look for the 99, what, if anything would you do to the array before searching it?
b. What is the index of the integer in the array that a binary search would examine first?
c. If all you dalmatians have more than 99 spots, exactly how many comparisons will binary search require to determine that 99 is not in the array?
for answer a, I would think to sort the array, but I am not sure if that is allowed because it says he first integer is the number of spots on the first dalmatian, the second integer is the number of spots on the second dalmatian, and so on.
for answer b, I thought you should split the array in half like I did in the search function, so I guess start with the middle index.
for answer c, would this be 50 comparisons?
Even though these answers do not need code I just want to show you that I thought about this
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
|
int main(){
int spot_array[101];
int size=101;
//sends to a function to enter the spots of the dalmatians
binarySearch(99);
system("Pause");
return 0;
}
void binarySearch(int spots[], int size, int key )
{
int position;
int comparisonCount = 1; //count the number of comparisons
int lowerbound=0, upperbound 100;
position = ( lowerbound + upperbound) / 2;
while((array[position] != key) && (lowerbound <= upperbound))
{
comparisonCount++;
if (array[position] > key)
{
upperbound = position - 1;
}
else
{
lowerbound = position + 1;
}
position = (lowerbound + upperbound) / 2;
}
if (lowerbound < = upperbound)
{
cout<< "The number was found in array subscript "<< position<<endl<<endl;
cout<< "The binary search found the number after " << comparisonCount
<< " comparisons.\n";
// printing the number of comparisons
}
else
cout<< "Sorry, the number is not in this array. The binary search made "
<<comparisonCount << " comparisons.";
return;
}
|