105k views
5 votes
Suppose that an array of strings contains ["blueberry", "chocolate", "coconut", "coffee", "mint", "strawberry", "vanilla"]. How many compares are used for a successful search for "mint" with binary search?

1 Answer

5 votes

Answer:

The answer is "4".

Step-by-step explanation:

In the given question the answer is "4" because the array of indexing always starts from the "0" position and the "mint" element value store in the fourth position.

This position can also be defined by the program code, which is defined in the below section. please find the code as well as its output.

program:

#include<iostream> //defining header file

using namespace std;

int BS(string Arr[], string val,int n) //defining method BS

{

int length=0 ;//defining integer variable length

int range = n-1; //defining range variable that takes one less value from n

while (length <= range)//defining while loop to check the length is less then equal to the range

{

int max=length+(range-length)/2;//defining max to store value

int rest; //defining integer variable rest

if (val == (Arr[max])) //defining if block that check val equal to Arr

{

rest= 0; //use rest variable to assign value 0

}

if (rest==0)//defining if block that check rest equal to 0

{

return max; //return max value

}

if (val > (Arr[max])) //defining if block that check val greater then Arr value

{

length=max+1; //use length variable that hold max+1 value

}

else //defining else block

{

range= max-1; //use range variable that hold max-1 value

}

}

return -1; //return value -1

}

int main()//defining main method

{

string Arr[]={"blueberry","chocolate","coconut","coffee","mint","strawberry","vanilla"};

string val = "mint"; //defining string variable val that store "mint" value

int n=7;//defining integer variable n that store array element value

cout<<BS(Arr,val,n); //use print method to call method "BS" and print value

}

output:

4

User Balkrishna
by
6.2k points