STL: Algorithm: binary_search ()



#include <algorithm>
#include <vector>
using namespace std;

int main ()
{
    int array [] = {5, 4, 1, 7, 9, 13, 32, 5, 71};
    int array_length = 9;

    vector <int> v ( array, array + array_length );
    // 5 4 1 7 9 13 32 5 71

    sort ( v.begin (), v.end () );
    // 1 4 5 5 7 9 13 32 71

    int key = 9;

    // binary_search() runs in logarithmic time
    if ( binary_search ( v.begin (), v.end (), key ) )
        printf ("key : %d found\n", key);
    else
        printf ("key : %d not found\n", key);

    key = 10;

    if ( binary_search ( v.begin (), v.end (), key ) )
        printf ("key : %d found\n", key);
    else
        printf ("key : %d not found\n", key);

    return 0;
}
/* output
key : 9 found
key : 10 not found

Process returned 0 (0x0)   
execution time : 0.046 s
Press any key to continue.
*/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s