Custopootimus

Quicksort w/ Immutable Stacks

Nov 4th, 2014
523
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.78 KB | None | 0 0
  1. public class Stack<T> {
  2.     /** Return true if the collection is empty */
  3.     public boolean isEmpty() { return true; }
  4.  
  5.     /** Return the top element on the stack */
  6.     public T peek() { return null; }
  7.            
  8.     /** Return the stack, sans top element */
  9.     public Stack<T> pop() { return this; }
  10.    
  11.     /** Return a new stack with a given item at the top */
  12.     public Stack<T> push(final T elem) {
  13.         return new Stack<T>() {
  14.             public T peek() { return elem; }
  15.             public Stack<T> pop() { return Stack.this; }
  16.             public boolean isEmpty() { return false; }
  17.         };}
  18. }
  19.  
  20. public static <T extends Comparable<T>> Stack<T> sort(Stack<T> stack) {
  21.  
  22.     if(stack.isEmpty())
  23.         return;
  24.    
  25.     T pivot = stack.peek();
  26.     stack = stack.pop();
  27.  
  28.     Stack<T>
  29.         lt = new Stack<T>(),
  30.         eq = new Stack<T>(),
  31.         gt  = new Stack<T>();
  32.    
  33.     while(!stack.isEmpty()) {
  34.         int comparison = stack.peek().compareTo(pivot);
  35.         if(comparison < 0)
  36.             lt = lt.push(stack.peek());
  37.         else if(comparison > 0)
  38.             gt = gt.push(stack.peek());
  39.         else
  40.             eq = eq.push(stack.peek());
  41.         stack = stack.pop();
  42.     }
  43.    
  44.     lt = reverse(sort(lt));
  45.     gt = reverse(sort(gt));
  46.    
  47.     for(;!gt.isEmpty(); gt=gt.pop())
  48.         stack = stack.push(gt.peek());
  49.        
  50.     for(;!eq.isEmpty(); eq=eq.pop())
  51.         stack = stack.push(eq.peek());
  52.        
  53.     for(;!lt.isEmpty(); lt=lt.pop())
  54.         stack = stack.push(lt.peek());
  55.        
  56.     return stack;
  57.    
  58. }
  59.  
  60. public static Stack<T> reverse(Stack<T> stack) {
  61.     Stack<T> rev = new Stack();
  62.     while(!stack.isEmpty()) {
  63.         rev.push(stack.peek());
  64.         stack = stack.pop();
  65.     }
  66.    
  67.     return rev;
  68. }
Advertisement
Add Comment
Please, Sign In to add comment