java实现堆栈排序_java-编写程序以按升序对堆栈进行排序

有人可以帮忙看看我的代码吗?非常感谢你的帮助.

输入堆栈为[5、2、1、9、0、10],我的代码给出了输出堆栈[0、9、1、2、5、10],9不在正确的位置.

import java.util.*;

public class CC3_6 {

public static void main(String[] args) {

int[] data = {5, 2, 1, 9, 0, 10};

Stack myStack = new Stack();

for (int i = 0; i < data.length; i++){

myStack.push(data[i]);

}

System.out.println(sortStack(myStack));

}

public static Stack sortStack(Stack origin) {

if (origin == null)

return null;

if (origin.size() < 2)

return origin;

Stack result = new Stack();

while (!origin.isEmpty()) {

int smallest = origin.pop();

int remainder = origin.size();

for (int i = 0; i < remainder; i++) {

int element = origin.pop();

if (element < smallest) {

origin.push(smallest);

smallest = element;

} else {

origin.push(element);

}

}

result.push(smallest);

}

return result;

}

}

最佳答案

/** the basic idea is we go on popping one one element from the original

* stack (s) and we compare it with the new stack (temp) if the popped

* element from original stack is < the peek element from new stack temp

* than we push the new stack element to original stack and recursively keep

* calling till temp is not empty and than push the element at the right

* place. else we push the element to the new stack temp if original element

* popped is > than new temp stack. Entire logic is recursive.

*/

public void sortstk( Stack s )

{

Stack temp = new Stack();

while( !s.isEmpty() )

{

int s1 = (int) s.pop();

while( !temp.isEmpty() && (temp.peek() > s1) )

{

s.push( temp.pop() );

}

temp.push( s1 );

}

// Print the entire sorted stack from temp stack

for( int i = 0; i < temp.size(); i++ )

{

System.out.println( temp.elementAt( i ) );

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值