How to sort a string with digits and letters (digits before letters) in Pascal

1 Answer

0 votes
program CustomSort;

function CompareChars(a, b: Char): Integer;
begin
  if (a in ['0'..'9']) and (b in ['A'..'Z', 'a'..'z']) then
    Exit(-1);
  if (a in ['A'..'Z', 'a'..'z']) and (b in ['0'..'9']) then
    Exit(1);
  Exit(Ord(a) - Ord(b));
end;

procedure CustomSort(var input: string);
var
  i, j: Integer;
  temp: Char;
begin
  for i := 1 to Length(input) - 1 do
    for j := i + 1 to Length(input) do
      if CompareChars(input[i], input[j]) > 0 then
      begin
        temp := input[i];
        input[i] := input[j];
        input[j] := temp;
      end;
end;

var
  input: string;
begin
  input := 'd25c4eb3a1';
  CustomSort(input);
  WriteLn('Custom sorted string: ', input);
end.
  
  
    
(*
run:
  
Custom sorted string: 12345abcde
    
*)

 



answered May 27, 2025 by avibootz
...