* Written By: Saurabh Tiwari
* Date: 11th May 2006
*
* Sorts a binary file using a Random Access External Sort. Uses the
* BUBBLE SORT algorithm (a simplified version of the SHELL SORT algorithm)
* to swap records in the file
*
*/
#include
class person_rec
{
friend class
donor_class;
private:
int id;
char name[20];
float fund;
};
class donor_class
{
private:
long num_of_rec;
public:
donor_class();
void bubble_sort();
void display();
};
//-----------------------------------------------------------------------
void main (void)
{
donor_class donor;
cout << "This is the file before sorting...\n\n";
donor.display();
donor.bubble_sort();
cout << "\nThis is the file after sorting...\n\n";
donor.display();
} // main
//-----------------------------------------------------------------------
donor_class::donor_class ()
{
person_rec rec;
fstream bifile ("a:\\a57h3g4.dat", ios::in | ios::binary);
bifile.seekg (0L, ios::end);
num_of_rec = bifile.tellg()/sizeof (rec);
cout << num_of_rec;
bifile.close();
} // constructor
//-----------------------------------------------------------------------
void donor_class::bubble_sort()
// swaps records into increasing order in a binary file
{
int i, not_sorted;
person_rec person1, person2, rec;
fstream bifile ("a:\\a57h3g4.dat", ios::in | ios::out | ios::binary);
do
{
not_sorted = 0;
for (i = 0; i < num_of_rec - 1; i = i + 1)
{
bifile.seekg ((i*sizeof(rec)), ios::beg);
bifile.read ((char *) &person1, sizeof (rec));
bifile.seekg (((i+1)*sizeof(rec)), ios::beg);
bifile.read ((char *) &person2, sizeof (rec));
if (person1.id > person2.id)
{
bifile.seekp ((i*sizeof(rec)), ios::beg);
bifile.write ((char *) &person2, sizeof (rec));
bifile.seekp (((i+1)*sizeof(rec)), ios::beg);
bifile.write ((char *) &person1, sizeof (rec));
not_sorted = 1;
} // if
} // for
}
while (not_sorted);
bifile.close();
} // bubble_sort
//-----------------------------------------------------------------------
void donor_class::display ()
// displays the file to the screen
{
person_rec person;
fstream infile ("a:\\a57h3g4.dat", ios::in | ios::binary);
while (infile.read((char *) &person, sizeof(person)))
{
cout << "ID: " << person.id << " Name: " << person.name;
cout << " Amount: $" << person.fund << endl;
} // while
infile.close();
} // display
No comments:
Post a Comment