Recent

Author Topic: Sort array of records  (Read 3298 times)

whiffee

  • New Member
  • *
  • Posts: 18
Sort array of records
« on: March 22, 2018, 01:44:16 am »
Hi All,
I'm trying to get started with records. I have read a number of things dealing with sorting an array of them,
but nothing at the simplistic level I need. The sorting I have in mind keeps the record fields together -- once a sorting field is chosen, all the fields adopt the same index. Offering the following flawed snippit. Trying to get the following output:

arp 0.21 2
arp 0.34 3
arp 0.501 1
arp 0.77 0

Code: Pascal  [Select][+][-]
  1. type
  2.   TPair = Record
  3.     sjac : Double;
  4.     indexx : Integer;
  5.   end;  

Code: Pascal  [Select][+][-]
  1. procedure Tform1.FillRecords(Sender: TObject);
  2. var r  : Integer;
  3.   begin
  4.  
  5.    arp[0].sjac := 0.34; arp[0].indexx := 3;
  6.    arp[1].sjac := 0.77; arp[1].indexx := 0;
  7.    arp[2].sjac := 0.21; arp[2].indexx := 2;
  8.    arp[3].sjac := 0.501; arp[3].indexx := 1;
  9.  
  10.    SortRecords(Sender);
  11.    for r := 0 to 3 do
  12.    output.Add( 'arp ' + FloattoStr(arp[r].sjac) + ' ' + InttoStr(arp[r].indexx));
  13. end;
  14.  
  15. procedure TForm1.SortRecords(Sender: TObject);
  16. var
  17.   p, q   : Integer;
  18.   index  : Double;
  19.  
  20. begin
  21.   for p := 0 to 3 do
  22.   begin
  23.     index := arp[p].sjac;
  24.     q := p;
  25.     while ((q > 0) AND (arp[q-1].sjac > index)) do
  26.     begin
  27.       arp[q].sjac := arp[q-1].sjac;
  28.       {arp[q].indexx := arp[q-1].indexx; **this line only does half of them}
  29.       q := q - 1;
  30.     end;
  31.     arp[q].sjac:= index;
  32.   end;
  33. end;                            
  34.  

taazz

  • Hero Member
  • *****
  • Posts: 5368
Re: Sort array of records
« Reply #1 on: March 22, 2018, 03:31:21 am »
Code: Pascal  [Select][+][-]
  1. procedure SwapRecords(var A :Array of TPair; Idx1, IDx2:integer);inline;
  2. var
  3.   vTmp: TPair;
  4. begin
  5.   vTmp      := arp[Idx1];
  6.   arp[Idx1] := arp[IDx2];
  7.   arp[idx2] := vTmp;
  8. end;
  9.  
  10. procedure TForm1.SortRecords(Sender: TObject);
  11. var
  12.   p, q   : Integer;
  13.   index  : Double;
  14.  
  15. begin
  16.   for p := 0 to 3 do
  17.   begin
  18.     index := arp[p].sjac;
  19.     q := p;
  20.     while ((q > 0) AND (arp[q-1].sjac > index)) do
  21.     begin
  22.       SwapRecords(arp, q, q-1);
  23.       q := q - 1;
  24.     end;
  25.     arp[q].sjac:= index;
  26.   end;
  27. end;                  
  28.  
Good judgement is the result of experience … Experience is the result of bad judgement.

OS : Windows 7 64 bit
Laz: Lazarus 1.4.4 FPC 2.6.4 i386-win32-win32/win64

whiffee

  • New Member
  • *
  • Posts: 18
Re: Sort array of records
« Reply #2 on: March 22, 2018, 04:19:10 am »
That's perfect, thanks muchly.


 

TinyPortal © 2005-2018