Search code examples
cmultidimensional-arrayswap

How to swap rows of 2D array


I am facing this situation for the first time and I would like to know if there is any "best way" or at least a good practice.

How to swap the rows of a 2D array?
For example:

FROM   -->   TO
1 1 1        2 2 2
2 2 2        1 1 1
3 3 3        3 3 3
  • Using memcpy?

  • Swapping the elements of the two rows one by one thanks to the good old for?

  • Having an array of dynamically allocated pointers to int (instead of the 2D array) and swap the pointers?

  • Some other way?


Solution

  • Using memcpy?

    That's probably a good tool to use for this if the data are in row-major order meaning each row is one contiguous block of memory. A fully general solution would need some upper bound on row size to avoid allocating a gigantic temporary row and thrashing the L1 cache (16 kB might be a reasonable maximum copy chunk size).

    Swapping the elements of the two rows one by one thanks to the good old for?

    That would be great for small rows or data which for other reasons must be stored in column-major order.

    Having an array of dynamically allocated pointers to int (instead of the 2D array) and swap the pointers?

    Certainly worth benchmarking, but unless row swapping is one of your main use cases, this may degrade performance of other operations so much as to be counter-productive.

    Here's one more alternative:

    Store the data contiguously in row-major order, but rather than moving the rows, keep a separate array of row indexes where each row is really stored. In your example that would be [1, 0, 2]. This would make row moves efficient like the pointer solution, while not slowing down other operations such as allocation, deallocation, summation, etc.