简体   繁体   中英

How do I sort a file of records using an insertion sort in pascal?

So I have a .dat file which consists of about twenty records. The fields of the record are: Name, Date and Score and I want to sort the records by score so that I can display them in a high score table. I am unsure of how to implement the sort so any help would be great. Thanks

Read the file into an array of records, inserting each record into the correct place. Then write the array back into the file.

The following is untested code, written off the top of my head. The key lines have been marked //** - the first line finds the correct place for the newly read record, the second line bumps all the records from that place onwards.

const
 maxrec = 50;

type
 MyRecord = record
             name: string[63];
             date: tdatetime;
             score: integer
            end;

var
 myfile: file of myrecord;
 rec: myrecord;
 data: array [1..maxrec] of myrecord;
 i, j, count: integer;

begin
 fillchar (data, sizeof (data), 0);
 assignfile (myfile, '.....');
 reset (myfile);
 read (myfile, rec);
 count:= 0;
 while not eof (myfile) do 
  begin
   i:= 1;
   while (i <= count) and (rec.score > data[i].score) do inc (i);   //**
   for j:= i to count do data[j+1]:= data[j];                       //**
   data[i]:= rec;
   inc (count);
  end;

 closefile (myfile);
 assignfile (myfile, '.......');
 rewrite (myfile);
 for i:= 1 to count do write (myfile, data[i]);
 closefile (myfile);
end;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM