The algorithm you talk about cannot possibly have a time and space complexity of O(N^2)
. I've specified my analysis below:
Algorithm 1 - Complexity: O(MN^2 log (MN^2))
This is the algorithm you've described.
1) Iterate over the matrix and pull each array to one Array: It will take O(M*N^2)
time to copy all the elements
2) After that sort this array. The fastest you could possibly sort is O(M*N^2 log (M*N^2))
.
Thus, the overall time complexity will be O(M*N^2 log (M*N^2))
.
Algorithm 2 - Complexity: O(MN^2 × log MN)
Adapted from Algorithm for n-way merge
- Create a priority queue
- Iterate through each array among the MxN arrays
- enqueue the pair (nextNumberIn({i,j}th array), {i,j}) using the first value as priority key
- While queue not empty
- dequeue head (
number
, {i,j}) of queue
- output
number
- if {i,j}th array not depleted
- enqueue (nextNumberIn({i,j}th array), {i,j})
Since adding elements to a priority queue can be done in logarithmic time, item 2 is O(M*N × log M*N)
. Since (almost all) iterations of the while loop adds an element, the whole while-loop will be O(M*N^2 × log M*N)
, where M*N^2 is the total number of elements to sort.
Since the complexity for step 3 dominates, the overall time complexity will be O(M*N^2 × log M*N)
.
Space Complexity
For both the algorithms above, the space complexity will be minimum of O(M*N^2)
to store the new array. In addition to that, algorithm #1 will require about O(log (M*N^2))
additional space for the sorting step, while algorithm #2 will require an additional space of O(M*N)
for the priority queue.