< previous page page_951 next page >

Page 951
void TimeCardList::BinSearch( /* in */  long      idNum,
                              /* out */ TimeCard& card,
                              /* out */ Boolean&  found ) const

// Precondition:
//     list[0..length-1] are in ascending order of employee ID
//  && idNum is assigned
// Postcondition:
//     IF time card for employee idNum is in list at position i
//         found == TRUE  &&  card == list[i]
//     ELSE
//         found == FALSE  && value of card is undefined

{
    int first = 0;           // Lower bound on list
    int last = length - 1;   // Upper bound on list
    int middle;              // Middle index

    found = FALSE;
    while (last >= first && !found)
    {
            // Invariant (prior to test):
            //     If idNum is in list[0..length-1] then
            //     idNum is in list[first..last]

        middle = (first + last) / 2;
        if (idNum < list [middle].IDPart())
            // Assert: idNum is not in list[middle..last]
            last = middle - 1;
        else if (idNum > list [middle].IDPart())
            // Assert: idNum is not in list[first..middle]
            first = middle + 1;
        else
            // Assert: idNum is in list[middle]
            found = TRUE;
    }
    if (found)
        card = list[middle];
}
Testing: If we step back and think about it, we realize that if we write a test driver for the TimeCardList class, we will have written the driver for the entire program! The big picture is that our program is to read in all the file data (function ReadAll), sort the time cards into order (function SelSort), and look up the time card information for various employees (function BinSearch). Therefore, we defer a discussion of testing until we have looked at the main driver.

 
< previous page page_951 next page >