GATE / CS ARCHIVE

GATE CSE 1995 / QUESTION 4(b)

Repair an in-place transpose

Data Structures · Arrays & Linked Lists · Full GATE CSE 1995 paper

GATE 1995, Q4(b) Descriptive
Report issue

Arrays & Linked Lists

Question 4(b), GATE 1995: An N×N integer array A (1<N≤20) is transposed by: for I:=1 to N−1 do for J:=1 to N do begin TMP:=A[I,J]; A[I,J]:=A[J,I]; A[J,I]:=TMP end. Find and correct the error.
Tap to enlarge
Answer & solution

Answer: Change the inner loop to J:=I+1 to N. (no official key was published)

Transposition must exchange each off-diagonal pair A[i,j], A[j,i] exactly once. In the supplied code, when i and j are both below N, the pair is exchanged once on iteration (i,j) and again on (j,i). The second exchange undoes the first. Pairs involving N are treated differently because the outer loop never reaches N. This is therefore not a valid general transpose, even though special inputs or N=2 can hide the fault.

Keep I from 1 through N−1 and change the inner loop to J from I+1 through N. The three assignments in the swap body can remain unchanged. Every unordered off-diagonal pair has exactly one representative with i<j, so it is visited once; diagonal entries need no work. The algorithm performs N(N−1)/2 swaps, takes Θ(N²) time and uses one temporary integer. Afterward every old A[i,j] has moved to A[j,i].

Original paper, page 6