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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,882 questions

51,808 answers

573 users

How to sort each column of a matrix with strings in Pascal

1 Answer

0 votes
program SortMatrixColumns;

uses
  SysUtils;

const
  ROWS = 4;
  COLS = 3;

type
  TMatrix = array[1..ROWS, 1..COLS] of string;
  TColumn = array[1..ROWS] of string;

// Function to sort an array of strings
procedure SortColumn(var Column: TColumn);
var
  i, j: Integer;
  temp: string;
begin
  for i := 1 to ROWS - 1 do
    for j := i + 1 to ROWS do
      //if CompareStrings(Column[i], Column[j]) > 0 then
      if CompareStr(Column[i], Column[j]) > 0 then
      begin
        temp := Column[i];
        Column[i] := Column[j];
        Column[j] := temp;
      end;
end;

// Function to sort each column of the matrix
procedure SortColumns(var Matrix: TMatrix);
var
  col, row: Integer;
  Column: TColumn;
begin
  for col := 1 to COLS do
  begin
    // Extract column values
    for row := 1 to ROWS do
      Column[row] := Matrix[row, col];

    // Sort the column
    SortColumn(Column);

    // Place sorted values back into the matrix
    for row := 1 to ROWS do
      Matrix[row, col] := Column[row];
  end;
end;

// Function to print the matrix
procedure PrintMatrix(const Matrix: TMatrix);
var
  row, col: Integer;
begin
  for row := 1 to ROWS do
  begin
    for col := 1 to COLS do
      Write(Matrix[row, col], ' ');
    Writeln;
  end;
end;

var
  Matrix: TMatrix = (
    ('ccc', 'zzzz', 'x'),
    ('eeee', 'aaa', 'ffff'),
    ('uu', 'hhh', 'uuu'),
    ('bbb', 'gg', 'yyyyyy')
  );

begin
  Writeln('Original Matrix:');
  PrintMatrix(Matrix);

  SortColumns(Matrix);

  Writeln(#10'Sorted Matrix:');
  PrintMatrix(Matrix);
end.

   
     
(*
run:
 
Original Matrix:
ccc zzzz x 
eeee aaa ffff 
uu hhh uuu 
bbb gg yyyyyy 

Sorted Matrix:
bbb aaa ffff 
ccc gg uuu 
eeee hhh x 
uu zzzz yyyyyy 
     
*)

 



answered Jun 2, 2025 by avibootz
...