package com.daelly.algorithm.stack.sort;
import java.util.Stack;
public class StackSort {
public static void stackSort(Stack<Character> s) {
if(s.isEmpty()) return;
char temp1= s.pop();
stackSort(s);
if(!s.isEmpty()) {
char temp2 = s.pop();
if(temp1 > temp2) {
s.push(temp1);
stackSort(s);
s.push(temp2);
}else {
s.push(temp2);
s.push(temp1);
}
} else {
s.push(temp1);
}
}
public static void main(String[] args) {
char[] list = {'3','4','2','1','6','5'};
Stack<Character> s = new Stack<>();
for (int i = 0; i < list.length; i++) {
s.push(list[i]);
}
System.out.println("Before sort:");
displayStack(s);
stackSort(s);
System.out.println("After sort:");
displayStack(s);
}
public static void displayStack(Stack<Character> s) {
Stack<Character> ss = new Stack<>();
while(!s.isEmpty()) {
char ch = s.pop();
ss.push(ch);
System.out.print(ch);
System.out.print("<-");
}
while(!ss.isEmpty()) {
s.push(ss.pop());
}
System.out.println();
}
}
栈的内排序
最新推荐文章于 2023-12-08 13:50:26 发布