給定一個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)
。
如果我的複雜度計算錯誤,請告訴我。
有沒有比這更高效的方法?