【发布时间】:2015-12-20 19:17:21
【问题描述】:
假设我有以下伪代码:
while A is not empty and stack top of A is less than x:
pop A and push the returned value onto B
push x onto A
while B is not empty:
pop B and push the returned valued onto A
假设堆栈 A 和 B 最初是空的。使用上述算法,每次插入 n 个数字和一个新数字 x,时间复杂度最差。
我能够得到这个算法会将长度为 n 的插入数字从最小(顶部)到最大(底部)排序,最好的情况是 n 当插入的数字已经排序时,从大到小。但我不明白最坏的情况是如何O(n^2)。
【问题讨论】:
-
x 是从哪里来的。
-
抱歉我遗漏了一些细节。
x是每次插入的数字。 -
这是一种笨拙的(可能是正式形式的)插入排序。这就是众所周知的 O(n^2)
标签: algorithm sorting stack big-o time-complexity