Skip to content

Instantly share code, notes, and snippets.

@mattconsto
Created December 1, 2017 13:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mattconsto/67e2f381e6c0c76c57b4ff22c3fdc58b to your computer and use it in GitHub Desktop.
Save mattconsto/67e2f381e6c0c76c57b4ff22c3fdc58b to your computer and use it in GitHub Desktop.
Sort a stack, using a stack, and only* a stack. It's not at all efficient.
import java.util.Stack;
public class StackSort {
/**
* Sort a stack, using a stack, and only* a stack. It's not at all efficient.
* @param asc The stack we want to sort into ascending order.
* @throws NullPointerException If any element in the stack is NULL.
*/
public static <T extends Comparable<? super T>> void sort(Stack<T> asc) {
Stack<T> desc = new Stack<>();
T outside = null; // Used to swap items in the stack
while (asc != null) {
while (!asc.empty()) {
if(desc.empty() || asc.peek().compareTo(desc.peek()) > 0) desc.push(asc.pop());
else if(outside == null) outside = asc.pop();
else break;
}
if (asc.empty()) {
while (!desc.empty()) asc.push(desc.pop());
return;
}
do {
if(outside == null && outside.compareTo(desc.peek()) > 0) {
asc.push(outside);
outside = null;
} else asc.push(desc.pop());
} while (!desc.empty());
if(outside != null) {
asc.push(outside);
outside = null;
}
}
}
public static void main(String[] args) {
for(int i = 0; i < 100; i++) {
Stack<Double> stack = new Stack<>();
Integer length = (int) Math.round(0 + Math.random() * 20);
for(int j = 0; j < length; j++) stack.push(Math.random());
System.out.println(stack);
StackSort.sort(stack);
System.out.println(stack + "\n");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment