How to sort a m x n matrix which has all its m rows sorted and n columns sorted?

后端 未结 3 2025
刺人心
刺人心 2020-12-14 09:20

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

相关标签:
3条回答
  • 2020-12-14 10:06

    I don't think you can do it any faster than Ω(m n log(min(m, n)), at least not in the general case.

    Suppose (without loss of generality) that m < n. Then your matrix looks like this:

    a matrix with rows and columns sorted

    Each circle is a matrix entry and each arrow indicates a known order relation (the entry at the source of the arrow is smaller than the entry at the destination of the arrow).

    To sort the matrix, we must resolve all the unknown order relations, some of which are shown in the grey boxes here:

    the order relations remaining to be resolved

    Sorting all of these boxes takes:

    2 Σk < m Ω(k log k) + (n - m + 1) Ω(m log m)

    = 2 Ω(m² log m) + (n - m + 1) Ω(m log m)

    = Ω(m n log m)

    0 讨论(0)
  • 2020-12-14 10:12

    By creating a Binary Search Tree, we can achieve this in O(mn) time. Take the last element from the first column (element 3 in the example mentioned above), make it as a root. Right nodes will be the n greater elements of that last row and left node will be the one above element ie. the (m-1)th or the 1st element from the second last row. Similarly for this element, the right nodes will be the n elements of that row. Again m-2 will be the left element and all the n elements in it's row will be the right elements. Similarly moving forward we'll have a binary search tree created in O(mn) time. This is O(mn) because we are not searching while inserting, it's a simple insert while traversing by shifting the root node pointer. Then inorder traversal of this BST will be done which will also be O(mn) time.

    0 讨论(0)
  • 2020-12-14 10:21

    If elements are integers within a certain range k where K=o(mn), we can use count sort with extra space to achieve O(mn), otherwise the mnlog(min(m,n)) is the best we can do.

    0 讨论(0)
提交回复
热议问题