[英]Sorting a stack using another stack
我想知道這個算法的時間復雜度,它用於使用另一個堆棧對堆棧進行排序。 我認為它是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;
}
如果排序堆棧[x_2, .., x_n]
(堆棧向右增長)花費t(n-1)
時間,排序堆棧[x_1, .., x_n]
時間將執行以下操作
s
子包[x_2, .., x_n]
x_1
到tmp
r
到s
最多轉移n-1
元素 x_1
推到r
因此,在[x_1, .., x_n]
上運行算法最多需要t(n-1) + O(n)
時間。 這導致(對於某些常數c
)
t(n) <= O(n) + t(n-1) <= c * n + t(n-1)
t(n) <= c * n + c * (n - 1) + t(n-2) <= ... <= c * (1 + 2 + ... + n)
t(n) <= c * n(n + 1) / 2
所以t(n)
是O(n^2)
。
看O(n ^ 2)給我。 我猜測已經排序的堆棧具有最差的性能。 我計算了s.push
執行的次數,給定已經排序的特定大小的堆棧。
Stack of size 1. backpushes: 0
Stack of size 2. backpushes: 1
Stack of size 3. backpushes: 3
Stack of size 4. backpushes: 6
Stack of size 5. backpushes: 10
Stack of size 6. backpushes: 15
Stack of size 7. backpushes: 21
Stack of size 8. backpushes: 28
Stack of size 9. backpushes: 36
0,1,3,6,10是三角數的序列。 大小為N的排序堆棧需要(N ^ 2 + N)/ 2個反推。 這使它成為O(N ^ 2)。
這個問題可以在o(n ^ 2)復雜度下完成。這可以在不使用彈出最大數字並在第二個堆棧中存儲rest元素並更新第一個堆棧的大小,然后推回到第一個堆棧的情況下完成。看看代碼段。
#include<stdio.h>
func(struct stack *s1)
{
struct stack* s2=(struct stack*) malloc(sizeof(struct stack))
int i=0;
int max=INT_MIN;
size=s1->size;
if(s1->size==0)
{
return;
}
for(;i<size;i++)
{
while(size(s1)!=size)//popping the elements and pushing in s2 stack and keeping track of maximum element.
{
temp=pop(s1);
if(temp>max)
{
push(s2,max);
max=temp;
}
}
push(s1,max);//pushing the max element into stack s1 back and updating the size in push operation.
while(!empty(s2))//pushing extracted numbers back into stack s1 from s2.
{
push(s1,pop(s2));
}
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.