给定一个2行数组(矩阵)与N行和K列,与它的行排序,列未指定,什么是最有效的算法来排序它?最有效的方法来排序2d数组排序到1d排序数组
对于〔实施例:
Input (n = 3 ; k = 4):
1 5 8 10
3 4 5 6
2 3 3 9
Output:
1 2 3 3 3 4 5 5 6 8 9 10
这是纯粹的算法问题,所以有些语言没有具体的.sort()方法,帮助我,因为我在运行复杂性实际上intereseted。
我脑子里想的是什么将是一个算法如下:
- Build a Binary Search tree with n nodes. Each node contains:
ID - of the row it refers to;
Value - The number at the "head" of the row.
- Sort the tree where the sorting key are the values.
- Find the lowest valued node.
- Do while the tree has a root:
- Take the lowest value and append it to the new array.
- Update the node's value to the next one in the same row.
- If the updated value is null, delete that node.
- else re-sort the tree.
- If the node moved, the first node it swapped with will be the next lowest
- else, if it didn't move, it's the new lowest.
如果我没有记错的运行时间复杂度为O(n*k * log n)
,由于我选树n*k
倍,这需要时间O(log n)
,并找到下一个最低的过程是O(1)
。
如果我的复杂度计算错误,请告诉我。
有没有比这更高效的方法?