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.](../../assets/questions/CS-1995-Q53-1.webp)
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].