Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth
Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

42,690 questions

55,449 answers

573 users

How to sort by numbers a mixed pair of string and number elements in an array with Pascal

1 Answer

0 votes
program SortByNumber;

const
  N = 7;

var
  Arr : array[1..N] of string;
  i, j : integer;
  num1, num2 : integer;

function ExtractNumber(s : string) : integer;
var
  p : integer;
  numStr : string;
begin
  { find last space }
  p := Length(s);
  while (p > 0) and (s[p] <> ' ') do
    Dec(p);

  numStr := Copy(s, p + 1, Length(s) - p);
  Val(numStr, ExtractNumber);
end;

procedure Swap(var a, b : string);
var
  t : string;
begin
  t := a;
  a := b;
  b := t;
end;

begin
  Arr[1] := 'Python 4';
  Arr[2] := 'C 9';
  Arr[3] := 'C++ 5';
  Arr[4] := 'C# 6';
  Arr[5] := 'Java 1';
  Arr[6] := 'PHP 7';
  Arr[7] := 'Go 2';

  { Bubble sort by numeric value }
  for i := 1 to N - 1 do
    for j := i + 1 to N do
    begin
      num1 := ExtractNumber(Arr[i]);
      num2 := ExtractNumber(Arr[j]);

      if num1 > num2 then
        Swap(Arr[i], Arr[j]);
    end;

  { Print result }
  for i := 1 to N do
    writeln(Arr[i]);
end.



(*
run:

Java 1
Go 2
Python 4
C++ 5
C# 6
PHP 7
C 9

*)

 



answered Jan 22 by avibootz

Related questions

...