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 search for a number in a sorted matrix in Pascal

2 Answers

0 votes
program MatrixSearch;

const
  Rows = 4;
  Cols = 5;

type
  TMatrix = array[1..Rows, 1..Cols] of Integer;

procedure MSearch(matrix: TMatrix; len, target: Integer);
var
  i, j: Integer;
begin
  i := 1;
  j := len;

  while (i <= Rows) and (j >= 1) do
  begin
    if matrix[i, j] = target then
    begin
      WriteLn('Found: i = ', i, ' j = ', j);  
      Exit;
    end;

    if matrix[i, j] > target then
      Dec(j)
    else
      Inc(i);
  end;

  WriteLn('Not found');
end;

var
  matrix: TMatrix;
begin
  matrix[1,1] := 2;  matrix[1,2] := 3;  matrix[1,3] := 5;  matrix[1,4] := 7;  matrix[1,5] := 8;
  matrix[2,1] := 10; matrix[2,2] := 13; matrix[2,3] := 17; matrix[2,4] := 18; matrix[2,5] := 19;
  matrix[3,1] := 25; matrix[3,2] := 26; matrix[3,3] := 30; matrix[3,4] := 37; matrix[3,5] := 38;
  matrix[4,1] := 43; matrix[4,2] := 46; matrix[4,3] := 50; matrix[4,4] := 51; matrix[4,5] := 99;

  MSearch(matrix, Cols, 37);
end.



(*
run:

Found: i = 3 j = 4

*)

 



answered Oct 7, 2025 by avibootz
0 votes
program MatrixSearch;

const
  Rows = 4;
  Cols = 5;

type
  TMatrix = array[0..Rows - 1, 0..Cols - 1] of Integer;

procedure MSearch(matrix: TMatrix; len, target: Integer);
var
  i, j: Integer;
begin
  i := 0;
  j := len - 1;

  while (i < Rows) and (j >= 0) do
  begin
    if matrix[i, j] = target then
    begin
      WriteLn('Found: i = ', i, ' j = ', j);
      Exit;
    end;

    if matrix[i, j] > target then
      Dec(j)
    else
      Inc(i);
  end;

  WriteLn('Not found');
end;

var
  matrix: TMatrix;
begin
  matrix[0,0] := 2;  matrix[0,1] := 3;  matrix[0,2] := 5;  matrix[0,3] := 7;  matrix[0,4] := 8;
  matrix[1,0] := 10; matrix[1,1] := 13; matrix[1,2] := 17; matrix[1,3] := 18; matrix[1,4] := 19;
  matrix[2,0] := 25; matrix[2,1] := 26; matrix[2,2] := 30; matrix[2,3] := 37; matrix[2,4] := 38;
  matrix[3,0] := 43; matrix[3,1] := 46; matrix[3,2] := 50; matrix[3,3] := 51; matrix[3,4] := 99;

  MSearch(matrix, Cols, 37);
end.



(*
run:

Found: i = 2 j = 3

*)

 



answered Oct 7, 2025 by avibootz
...