Given a matrix with m rows and n columns, each of which are sorted. How to efficiently sort the entire matrix?
I know a solution which runs in O(m n log(min(m,n)). I am looking for a better solution.
The approach that I know basically takes 2 rows/cols at a time and applies merge operation.
Here is an example:
[[1,4,7,10],
[2,5,8,11],
[3,6,9,12]]
is the input martix which has every row and column sorted.
Expected output is:
[1,2,3,4,5,6,7,8,9,10,11,12]
Another example:
[[1, 2, 3, 3, 4, 5, 6, 6, 7, 7],
[1, 2, 4, 6, 7, 7, 8, 8, 9,10],
[3, 3, 4, 8, 8, 9,10,11,11,12],
[3, 3, 5, 8, 8, 9,12,12,13,14]]
See Question&Answers more detail:
os