Is binary search possible with Vectors?

I've been trying to implement it all day. But can't seem to convert an Array based bit of code.

1
2
3
4
5
6
7
8
9
10
11
12
13
int binarySearch(int sortedArray[], int first, int last, int key) {
    
   while (first <= last) {
       int mid = (first + last) / 2;  // compute mid point.
       if (key > sortedArray[mid]) 
           first = mid + 1;  // repeat search in top half.
       else if (key < sortedArray[mid]) 
           last = mid - 1; // repeat search in bottom half.
       else
           return mid;     // found it. return position /////
   }
   return -(first + 1);    // failed to find key
}


Thanks for any help
There is a built in binary search algorithm for STL containers:

http://www.cplusplus.com/reference/algorithm/binary_search.html
Note that binary searches require the container to be sorted beforehand. STL vectors are not sorted by default.

Sort the vector first, and then it will work.

Alternatively, a set is a sorted container and I believe that its find method is implemented as a binary search.
Topic archived. No new replies allowed.