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,907 questions

51,839 answers

573 users

How to calculate the median of a matrix in Pascal

1 Answer

0 votes
program MedianMatrix;

const
  ROWSCOLS = 4;
  TOTAL = ROWSCOLS * ROWSCOLS;

type
  MatrixType = array[1..ROWSCOLS, 1..ROWSCOLS] of integer;
  ArrayType = array[1..TOTAL] of integer;

// Step 2: Sort the elements
procedure SortMatrix(var elements: ArrayType; total: integer);
var
  i, j, temp: integer;
begin
  for i := 1 to total - 1 do
    for j := i + 1 to total do
      if elements[i] > elements[j] then
      begin
        temp := elements[i];
        elements[i] := elements[j];
        elements[j] := temp;
      end;
end;

// Step 1: Flatten the matrix into a single array
function FindMedianUnsortedMatrix(matrix: MatrixType; rows, cols: integer): real;
var
  elements: ArrayType;
  i, j, k, total: integer;
  median: real;
begin
  total := rows * cols;
  k := 1;

  for i := 1 to rows do
    for j := 1 to cols do
    begin
      elements[k] := matrix[i, j];
      inc(k);
    end;

  // Step 2: Sort the elements
  SortMatrix(elements, total);

  // Step 3: Calculate median
  if total mod 2 = 1 then
    // Odd number of elements: return middle element
    median := elements[(total div 2) + 1]
  else
    // Even number of elements: return average of two middle elements
    median := (elements[total div 2] + elements[(total div 2) + 1]) / 2.0;

  FindMedianUnsortedMatrix := median;
end;

var
  matrix: MatrixType;
  median: real;
begin
  matrix[1,1] := 5;  matrix[1,2] := 8;  matrix[1,3] := 9;  matrix[1,4] := 10;
  matrix[2,1] := 1;  matrix[2,2] := 4;  matrix[2,3] := 6;  matrix[2,4] := 13;
  matrix[3,1] := 7;  matrix[3,2] := 3;  matrix[3,3] := 0;  matrix[3,4] := 18;
  matrix[4,1] := 6;  matrix[4,2] := 8;  matrix[4,3] := 9;  matrix[4,4] := 20;

  median := FindMedianUnsortedMatrix(matrix, ROWSCOLS, ROWSCOLS);
  writeln('Median of the matrix is: ', median:0:1);
end.



(*
run:

Median of the matrix is: 7.5

*)

 



answered Oct 5, 2025 by avibootz
...