CSE 40872 Lecture 011

Topic:Searching
Author: Peter Bui <pbui@cse.nd.edu>
Date: September 25, 2009

Searching

Scanning a collection is O(n), and relatively straightforward.

If we have to do multiple searches, then we can sort a container and then perform binary search for subsequent searches O(logn).

Searching (C)

void *bsearch(const void *key, const void *base,
              size_t nmemb, size_t size,
              int (*compar)(const void *, const void *));

int  ia[6] = { 0, 1, 2, 3, 4, 5 };
int  ik;
int *ip;

qsort(ia, 6, sizeof(int), int_cmp);

ik = 4;
ip = bsearch(&ik, ia, 6, sizeof(int), int_cmp);

if (ip) printf("found %d in integer array\n", ik);

Searching (STL)

if (binary_search(iv.begin(), iv.end(), 4))
    cout << "found 4 in integer vector" << endl;

vector<int>::iterator it;
it = lower_bound(iv.begin(), iv.end(), 4);
if (it != iv.end())
    cout << "found 4 in integer vector" << endl;

sv.push_back(3); sv.push_back(4), sv.push_back(5);
if (includes(iv.begin(), iv.end(), sv.begin(), sv.end()))
    cout << "iv contains all of sv" << endl;