Page 1 of 1
Forum

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



Share:
Notifications
Clear all

[Solved] Lazarus Pascal - QuickSort TStringList to QuickSort Array of Records

1 Posts
1 Users
0 Likes
4,579 Views
 Hans
(@hans)
Famed Member Admin
Joined: 11 years ago
Posts: 2703
Topic starter  

I ran into this very nice looking code for a QuickSort routine in Lazarus Pascal:

procedure QuickSort(var A: TStringList);
  procedure Sort(L, R: Integer);
  var
    I, J: Integer;
    Y, X:string;
  begin
    I:= L; J:= R; X:= A[(L+R) DIV 2];
    repeat
      while StrIcomp(pchar(A),pchar(X))<0 do inc(I);
      while StrIComp(pchar(X),pchar(A[J]))<0 do dec(J); 
      if I <= J then
      begin
        Y:= A; A:= A[J]; A[J]:= Y;
        inc(I); dec(J);
      end;
    until I > J;
    if L < J then Sort(L,J);
    if I < R then Sort(I,R);
  end;
begin
  Sort(0,A.Count-1);
end;

It's written to sort a TStringList and called as such:

QuickSort(MyStringList);

Unfortunately, this is not what I needed.
I wanted to sort an array of records.

So below my adapted version of this code for an array:

TSomeLanguage = record
    abbreviation: string;
    name: string;
    englishName: string;
  end;
...
SomeLanguages : array of TSomeLanguage;
...
procedure TNMTVForm.QuickSortLanguages(var A: array of TSomeLanguage);
    procedure Sort(L, R: Integer);
    var
      I, J: Integer;
      Y, X: TTVDBSeries;
    begin
      I:= L; J:= R; X:= A[(L+R) DIV 2];
      repeat
        while StrIcomp(pchar(A.englishName),pchar(X.englishName))<0 do inc(I); // <-- adapt to your array
        while StrIComp(pchar(X.englishName),pchar(A[J].englishName))<0 do dec(J); // <-- adapt to your array 
        if I <= J then
        begin
          Y:= A; A:= A[J]; A[J]:= Y;
          inc(I); dec(J);
        end;
      until I > J;
      if L < J then Sort(L,J);
      if I < R then Sort(I,R);
    end;
begin
  Sort(0,length(A)-1);
end;

...

QuickSortLanguages(SomeLanguages);

...

This will sort the array "SomeLanguages" based on the field "englishName".
You can see the 2 lines in the code which you may have to alter for the array you'd defined.

Hope this is helpful for anyone looking to sort their arrays ... 


   
ReplyQuote
Share: