【发布时间】:2015-01-14 10:50:24
【问题描述】:
我想知道该算法的时间复杂度,该算法用于使用另一个堆栈对堆栈进行排序。我以为是 O(N^2),但显然它看起来不止于此。
public static Stack<Integer> sort(Stack<Integer> s) {
Stack<Integer> r = new Stack<Integer>();
while(!s.isEmpty()) {
int tmp = s.pop();
while(!r.isEmpty() && r.peek() > tmp) {
s.push(r.pop());
}
r.push(tmp);
}
return r;
}
【问题讨论】:
-
尝试找出一个输入(s的内容),这将是该算法最坏的情况
-
在我看来它应该是 O(n^2),是什么让你认为它不是?
标签: performance algorithm sorting complexity-theory time-complexity