binary search

I was told that the output can either be 11 or 10, but when I compile&run the code below, I only get 10 and I do not understand why the output is 10 instead 11.
I thought the code was simply searching for the integer 4, and hence should output true for both searches resulting in 11.
Can someone explain. Thanks in advance.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <deque>
#include <list>
#include <algorithm>
#include <set>
#include <queue>
#include <vector>
using namespace std;

template<class T> struct Out{
    ostream & out;
    Out(ostream & o): out(o){}
    void operator() (const T & val) {out<<val<<"";}};
    
int main(){
    int t[]={8,10,5,1,4,6,2,7,9,3};
    deque<int>d1(t,t+10);
    set<int>s1(t,t+10);
    cout<<binary_search(s1.begin(),s1.end(),4)<<""<<binary_search(d1.begin(),d1.end(),4)<<endl;
    
    
    return 0;

}
Last edited on
std::binary_search requires a partitioned (or, to keep it simple, sorted) sequence.
[s1.begin(), s1.end()) is sorted, [d1.begin(), d1.end()) is not.

If you insert the line sort(d1.begin(), d1.end()); between lines 17 and 19, you will get the 11
Last edited on
Yes, you cannot perform a binary search on unsorted sequence, that's fairly obvious if you check out the algorithm:
http://en.wikipedia.org/wiki/Binary_search_algorithm
Topic archived. No new replies allowed.