假设我有一个元素按升序排列的队列,即head<第二<第3< ......<尾
和具有降序元素的堆栈,即顶部>第二个> 3> ...
它们的大小最多相差1(它们可能大小相同)。
将它们合并到同一队列(或堆栈)中作为单个排序序列的最有效方法是什么?没有额外的堆栈/队列?
到目前为止,我认为最好的是基本选择排序的二次算法,它并没有真正利用队列和堆栈预先排序的事实及其大小。我想知道我们能做得更好吗?
答案 0 :(得分:0)
只需合并到位,将结果放在队列的末尾。保持计数,以便知道何时结束。这是O(n)。
这是在python中。我没有使用队列或堆栈类,但你会看到q列表是FIFO,s列表是LIFO!
启用了最有趣的调试案例,以便您可以看到输出。
def sort(Q, S, debug=False):
q = Q
s = S
size = len(Q) + len(S)
handled = 0
while handled < size:
move_from_queue = len(s) == 0 or (len(q) > 0 and q[0] < s[0])
last_from_stack = (handled == size-1) and (len(s) == 1)
if move_from_queue and not last_from_stack:
q_front = q[0]
q = q[1:] + [q_front]
msg = 'moved q[0]=%d to end, q=%r' % (q_front, q)
else:
(s_top, s) = (s[0], s[1:])
q += [s_top]
msg = 'popped s[0]=%d to end of q=%r,s=%r' % (s_top, q, s)
handled += 1
if debug:
print 'Debug-Step %d: %s' % (handled, msg)
return (q, s)
def test_sort(Q, S, debug=False):
print 'Pre Q: %r' % Q
print 'Pre S: %r' % S
(Q, S) = sort(Q, S, debug)
print 'Sorted: %r' % Q
print
if __name__ == "__main__":
test_sort([1, 3, 7, 9], [2, 5, 5])
test_sort([1, 3, 7], [2, 5, 5])
test_sort([1, 3, 7], [2, 5, 5, 9], True)
test_sort([], [])
test_sort([1], [])
test_sort([], [1])
输出:
Pre Q: [1, 3, 7, 9] Pre S: [2, 5, 5] Sorted: [1, 2, 3, 5, 5, 7, 9] Pre Q: [1, 3, 7] Pre S: [2, 5, 5] Sorted: [1, 2, 3, 5, 5, 7] Pre Q: [1, 3, 7] Pre S: [2, 5, 5, 9] Debug-Step 1: moved q[0]=1 to end, q=[3, 7, 1] Debug-Step 2: popped s[0]=2 to end of q=[3, 7, 1, 2],s=[5, 5, 9] Debug-Step 3: moved q[0]=3 to end, q=[7, 1, 2, 3] Debug-Step 4: popped s[0]=5 to end of q=[7, 1, 2, 3, 5],s=[5, 9] Debug-Step 5: popped s[0]=5 to end of q=[7, 1, 2, 3, 5, 5],s=[9] Debug-Step 6: moved q[0]=7 to end, q=[1, 2, 3, 5, 5, 7] Debug-Step 7: popped s[0]=9 to end of q=[1, 2, 3, 5, 5, 7, 9],s=[] Sorted: [1, 2, 3, 5, 5, 7, 9] Pre Q: [] Pre S: [] Sorted: [] Pre Q: [1] Pre S: [] Sorted: [1] Pre Q: [] Pre S: [1] Sorted: [1]