Created
December 1, 2017 13:00
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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