Slide 8.9: Keysorting
Slide 8.11: Keysort.cpp
Home

Keysorting (Cont.)

Algorithm of a Keysort

int  KeySort( FixedRecordFile& inFile, char* outFileName ) {
  RecType obj;
  KeyRRN* KEYNODES = new KeyRRN[ inFile.NumRecs( ) ];
  // read file and load Keys
  for ( int i = 0;  i < inFile.NumRecs( );  i++ ) {
    inFile.ReadByRRN( obj, i );             // read record i
    KEYNODES[i] = KeyRRN( obj.Key( ), i );  // put key and RRN into Keys
  }
  Sort( KEYNODES, inFile.NumRecs( ) );      // sort Keys
  FixedRecordFile  outFile;        // file to hold records in key order
  outFile.Create(outFileName);            // create a new file
  // write new file in key order
  for ( int j = 0;  j < inFile.NumRecs( );  j++ ) {
    inFile.ReadByRRN( obj, KEYNODES[j].RRN );   //  read in key order
    outFile.Append  ( obj );                    // write in key order
  }
  return  1;
}

This algorithm works much the same way that a normal internal sort would work, but with two important differences: Finally, a problem of keysorting is observed and a solution is proposed: