Slide 8.6: SkipSpaces.h
Slide 8.8: Internal sorting
Home

Binary.cpp


The code below is the implementation of the main function of a binary search whose algorithm is given on the Slide 8.1. Note that the length of the first record number + ' ' + length + '\n' is 12.

 ~wenchen/public_html/cgi-bin/351/week8/Binary.cpp 
#include  <fstream>
#include  <iostream>
#include  <cstring>
  using namespace  std;

#include  "Book_1.h"
#include  "Overload.h"
int  main( int argc, char* argv[ ] ) {
  fstream  file;
  Book     b;
  int      length, low, high, guess, result, count;
  char     title[129], buffer[129];

  strcpy( title, argv[1] );
  file.open( "books.txt", fstream::in );
  file >> high >> length;
  low  = count = 1;
  while ( low <= high ) {
    guess = ( high + low ) / 2;
    file.seekg( 12+(guess-1)*length, fstream::beg );
    file >> b;
    cout << count++ << " comparisons; checking title: ";
    cout << b.GetValue( 1, buffer ) << "<br />";
    if ( ( result = strcmp( title, buffer ) ) == 0 ) {
      b.PutResults( );
      break;
    }
    else if ( result < 0 )
      high = guess - 1;
    else
      low  = guess + 1;
  }
  if ( low > high ) {
    cout << "<br /><h3>No such book: <em>" << title << "</em></h3>";
  }
  file.close( );
}