Questions 2,4,5,10

Q2. Algorithms STL#2
Choose the correct output and time complexity for the following code :

list< int > myList = { 2, 6, 12, 13, 15, 18, 20};
cout << binary_search(myList.begin(), myList.end(), 20) ;
Output is 20 and time complexity is Linear in size of the list.

Output is 1 and time complexity is Linear in size of the list.

Output is 20 and time complexity is Logarithmic in size of the list.

Output is 1 and time complexity is Logarithmic in size of the list.

Q4. Algorithms STL#4
What is the data type that should be returned by a comparator? If we would like to see item1 before item2 in our final sorted ordering then compare(item1, item2) should return what value?

bool and 0

int and any positive number

bool and 1

int and any number but 0.

Q5 Given the following code snippet :

bool comp(string s1, string s2)
{
if(s1.length() < s2.length())
return 1;
else if(s1.length() > s2.length())
return 0;
else return s1 < s2;
}

vector< string > data = {“b”, “a”, “c”, “abc”, “bca”, “xy”};
sort(data.begin(), data.end(), comp);
for(string item : data)
cout << item << " ";

Choose the correct output :

a b c abc bca xy

xy bca abc c b a

a b c xy abc bca

b a c xy abc bca

Q10. Algorithms STL#10
Given the following code snippet :

string s = “bca”;

do {
cout << s << ’ ';
} while(next_permutation(s.begin(), s.end()));

cout << s;
What is the output of the given code?

bca cab cba abc

bca cab cba cba

bca bca bca bca

bca cab cba bca

@ysurange1998 in question 2, you are searching for 20 in a “linked list”, not an array, so you cant simply go back and forth like you would in an array, this is why linear search has to be used.

In q4, bool and 1, is the answer because return type of comp function is bool and for ascending values, item 1 should be less than item 2, (assuming that item1 occurs before item2) this is why item1 < item2 returns true.

in q5, in compare function, true value indicates that the condition should be used for sorting the elements, ie all the pairs of the container should follow that condition, similarly if it were false then all the pairs should NOT follow that condition.

in q10 what do you mean by “wrap around”?

1 Like

Wrap around - after all the permutations are finished , the first permutation will again be displayed as in this case abc.

@ysurange1998 yes it does.

see the example here http://www.cplusplus.com/reference/algorithm/next_permutation/

please mark your doubt as resolved if you are satisfied.

1 Like

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.

sir, wherw to seek for q5 sol explanation?