martedì 11 febbraio 2014

Efficiently swap matrix rows and columns synchronously

It may happen (practical and usual examples?) that you have a matrix data structure and you need to (synchronously) swap rows i and j together with columns i and j.

The simple solution would require to iterate on the rows/columns entries, so it costs O(n) for an n x n matrix (similar considerations if the matrix is rectangular).

A more clever solution adopts an additional vector of size n and works in O(1). The idea is to keep the additional vector ind as a sort of array of pointers to the rows/columns of the matrix m.  In the following, the three main aspects of the solution:
  1. Vector ind has to be initialized to the "identity" vector (ind = <0, 1, ..., n-1>).
  2. Access m entries no more directly but through ind, i.e. m[ind[i],ind[j]] instead of the classical m[i,j].
  3. Now, the swap of both rows and columns i and j can be done by simply swapping ind[i] and ind[j].

Nessun commento:

Posta un commento