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!
[Solved] Lazarus Pascal - Quicksort an Array of string, by the length of the strings
Delphi, Lazarus, Free Pascal
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2999
Topic starter
October 10, 2025 11:46 AM
Had to write a procedure that sorts an array of strings (dynamic) by the length of the individual strings.
Thought someone may find this useful:
// QuickSort array of string by string length
procedure QuickSortByLength(ListOfStrings: array of string; Start: integer = -1; Stop: Integer = -1);
var
i, j, PivotLen: Integer;
Pivot: string;
Temp: string;
begin
if (Start=-1) or (Stop=-1) then
begin
Start := 0;
Stop := Length(ListOfStrings)-1;
end;
i := Start;
j := Stop;
Pivot := ListOfStrings[(Start + Stop) div 2];
PivotLen := Length(Pivot);
repeat
while Length(ListOfStrings[i]) < PivotLen do Inc(i);
while Length(ListOfStrings[j]) > PivotLen do Dec(j);
if i <= j then
begin
Temp := ListOfStrings[i];
ListOfStrings[i] := ListOfStrings[j];
ListOfStrings[j] := Temp;
Inc(i);
Dec(j);
end;
until i > j;
if Start < j then QuickSortByLength(ListOfStrings, Start, j);
if i < Stop then QuickSortByLength(ListOfStrings, i, Stop);
end;
I did write it so that when you pass only an array, it will sort the entire array.
Calling this function:
...
var
MyStrings : array of string;
...
// sort entire list automatically
QuickSortByLength(MyStrings);
...
// sort entire list manually
QuickSortByLength(MyStrings, 0, length(MyStrings)-1);
...
// sort only a section
QuickSortByLength(MyStrings, 5, 10);
...