How to sort a string in the order: lowercase letters - uppercase letters - odd digits - even digits in Pascal

1 Answer

0 votes
program SortAlphaNumeric;

{$mode objfpc}{$H+}{$J-}

{
    We want to sort characters in this strict order:
    1. lowercase letters   (a–z)
    2. uppercase letters   (A–Z)
    3. odd digits          (1,3,5,7,9)
    4. even digits         (0,2,4,6,8)

    Free Pascal does NOT support TStringList.OnCompare (Delphi only),
    so we implement our own QuickSort with a custom comparator.
}

type
    TCharArray = array of Char;


/// Returns category rank for sorting.
/// Lower rank = comes earlier.
function Category(c: Char): Integer;
var
    d: Integer;
begin
    if (c >= 'a') and (c <= 'z') then Exit(0);   // lowercase
    if (c >= 'A') and (c <= 'Z') then Exit(1);   // uppercase
    if (c >= '0') and (c <= '9') then
    begin
        d := Ord(c) - Ord('0');
        if (d mod 2 = 1) then Exit(2) else Exit(3);  // odd / even digits
    end;
    Exit(4); // fallback (should not occur)
end;

/// Custom comparator: returns TRUE if a < b
function Less(a, b: Char): Boolean;
var
    ca, cb: Integer;
begin
    ca := Category(a);
    cb := Category(b);

    if ca <> cb then
        Exit(ca < cb);   // category decides

    Result := a < b;     // tie-breaker: natural order
end;


/// In-place QuickSort for character array
procedure QuickSort(var A: TCharArray; L, R: Integer);
var
    i, j: Integer;
    pivot, temp: Char;
begin
    i := L;
    j := R;
    pivot := A[(L + R) div 2];

    repeat
        while Less(A[i], pivot) do Inc(i);
        while Less(pivot, A[j]) do Dec(j);

        if i <= j then
        begin
            temp := A[i];
            A[i] := A[j];
            A[j] := temp;
            Inc(i);
            Dec(j);
        end;
    until i > j;

    if L < j then QuickSort(A, L, j);
    if i < R then QuickSort(A, i, R);
end;


var
    S: String;
    A: TCharArray;
    i: Integer;

begin
    S := 'a2B3cD8f1Z0';

    { Convert string to dynamic array of chars }
    SetLength(A, Length(S));
    for i := 1 to Length(S) do
        A[i-1] := S[i];

    { Sort using our custom QuickSort }
    QuickSort(A, 0, High(A));

    { Rebuild string }
    S := '';
    for i := 0 to High(A) do
        S := S + A[i];

    WriteLn('Sorted result: ', S);
end.


{
run:

Sorted result: acfBDZ13028

}

 



answered Jul 14 by avibootz

Related questions

...