Stack(5)对栈排序不用循环空间复杂度O(1)

来源:互联网 发布:正规网络彩票关注网站 编辑:程序博客网 时间:2024/05/18 17:43

对栈stack排序,不能使用循环while,for等,只能使用Stack的以下方法(Java版本)

isEmpty():判断堆栈是否为空。push(S):将新元素添加到堆栈。pop(S):从堆栈中删除顶层元素。peek(S):返回顶元素的值。

输入:-3 <---顶部        14         18         -5         30 输出:30 <---顶部        18         14         -3         -5 

算法:

sortStack(Stack S)    如果堆栈不为空:        temp = pop(S);          sortStack(S);         sortedInsert(S,temp);
sortedInsert(Stack S, element)    如果栈为空 或者element > top element        push(S, elem)    else        temp = pop(S)        sortedInsert(S, element)        push(S, temp)

例子
给定堆栈为
-3 < - 堆栈顶部
14
18
-5
30
让我们用上面的例子说明堆栈的排序:
首先从堆栈中弹出所有元素,并将pop()元素存储在变量’temp’中。在弹出所有元素功能的堆栈框架将看起来像:

temp = -3 - >堆栈帧#1
temp = 14 - >堆栈帧#2
temp = 18 - >堆栈帧#3
temp = -5 - >堆栈帧#4
temp = 30 - >堆栈帧#5

现在堆栈是空的,并且’insert_in_sorted_order()’函数被调用,并且在堆栈的底部插入30个(来自堆栈帧#5)。现在堆栈看起来如下:

30 < - 堆栈顶部
现在选择下一个元素即-5(来自堆栈帧#4)。由于-5 <30,-5插入堆栈的底部。现在堆栈变成:

30 < - 堆栈顶部
- 5
选择下一个18(来自堆栈帧#3)。由于18 <30,18被插入30以下。现在堆成为:

30 < - 堆栈顶部
18
-5
选择下一个14(来自堆栈帧#2)。自14 <30和14 <18以来,它被插入到18以下。现在堆栈变成:

30 < -所述堆叠的顶部
18 14
-5
现在-3(来自堆栈帧#1)被选择为-3 <30和-3 <18和-3 <14,它被插入到14以下。现在栈变成:

30 < -所述堆叠的顶部
18
14
-3
-5


代码


package Stack;import java.util.Stack;public class SortStack {    public static void main(String[] args) {        int array[]={-3,14,18,-5,30};        Stack< Integer> stack=new Stack<Integer>();        int i=0;        while(i<array.length)        {            stack.push(array[i++]);        }        Sort(stack);        while(!stack.isEmpty())        {            System.out.println(stack.pop());        }    }    public static void Sort(Stack< Integer> stack)    {        if(!stack.isEmpty())        {            int temp=stack.pop();            Sort(stack);            InsertSort(stack,temp);        }       }    public static void InsertSort(Stack<Integer> stack,int Elem)    {        if(stack.isEmpty()||Elem>stack.peek())        {            stack.push(Elem);        }        else {            int temp=stack.pop();            InsertSort(stack, Elem);            stack.push(temp);        }    }}
0 0
原创粉丝点击