//----------------------------------------------------------------------
//  IMPLEMENTATION FILE (binsrch2.cpp)
//  This module exports a single Lookup function to search
//  an integer vector for a particular value.
//----------------------------------------------------------------------
#include "binsrch2.h"

//  Algorithm: an improved version of the binary search
//
//  Note: The precondition differs from the linear search version.
//        vec must already be sorted into ascending order, and
//        there is a limit on vSize: half the maximum int value.

void Lookup( /* in */  const int vec[],
             /* in */  int       vSize,
             /* in */  int       key,
             /* out */ Boolean&  found,
             /* out */ int&      loc   )

    // PRE:  0 <= vSize <= (maximum int)/2  &&  Assigned(key)
    //    && vec[0..vSize-1] are in ascending order
    // POST: (found) --> vec[loc] == key
    //    && (NOT found) --> No vec[0..vSize-1] == key
    //                      && loc is undefined
{
    int lowerIndex = 0;
    int upperIndex = vSize - 1;

    while (lowerIndex < upperIndex) {
                            // INV (prior to test):
                            //    If key is in vec[0..vSize-1] then
                            //    key is in vec[lowerIndex..upperIndex]
        loc = (upperIndex + lowerIndex) / 2;
        if (key > vec[loc])
            lowerIndex = loc + 1;
        else
            upperIndex = loc;
    }
    loc = lowerIndex;
    found = (vSize > 0 && vec[loc] == key);
}


