GATE / CS ARCHIVE

GATE CSE 1993 / QUESTION 12

Complete a single-loop matrix maximum

Algorithms · Correctness, Invariants & Design · Full GATE CSE 1993 paper

GATE 1993, Q12 5 marks · Descriptive
Report issue

Correctness, Invariants & Design

Question 12, GATE 1993: For integer A[0..n-1,0..n-1], complete four boxes in: max:=[A]; i:=0; j:=0; while [B] do begin if A[i,j]>max then max:=A[i,j]; if [C] then j:=j+1 else begin j:=0; i:=[D] end end. Use a single loop to find the largest entry. The source's comma/semicolon punctuation is defective; boxes A–D are one coordinated question.
Tap to enlarge
Answer & solution

Answer: A=A[0,0]; B=i<n; C=j<n−1; D=i+1 (n>=1). (no official key was published)

For n>=1 choose box A=A[0,0], B=(i<n), C=(j<n-1), D=i+1. Initializing to the first entry rather than 0 is important: all entries may be negative. The fully punctuated Pascal-style segment is:

begin
  max := A[0,0];
  i := 0; j := 0;
  while i < n do
  begin
    if A[i,j] > max then max := A[i,j];
    if j < n-1 then
      j := j+1
    else
    begin
      j := 0;
      i := i+1
    end
  end
end.

The pair (i,j) moves in row-major order: (0,0),(0,1),...,(0,n-1),(1,0),..., (n-1,n-1). At a row's last column, j is reset before proceeding to the next row. After the final element the state becomes (n,0); the guard stops before any invalid A[n,0] access.

Correctness invariant: immediately before processing each cell, max is the maximum of A[0,0] and every previously visited cell. The comparison incorporates the current cell and preserves this property. The rank n*i+j increases by exactly 1 per iteration and begins at 0, so exactly n2 cells are visited. On exit the invariant gives the maximum over the entire array. For n=1 the first entry is compared with itself once and the program exits correctly. Time is Theta(n2), extra space Theta(1). The n=0 case has no maximum and must be rejected or handled outside this segment; the printed task implicitly needs a nonempty array.

Original paper, page 11