fork download
  1. import java.util.Stack;
  2. /**
  3.  * Recursive Inplace Stack Sorting
  4.  * @author Prateek
  5.  */
  6. class SortStack {
  7.  
  8. //input stack
  9. private Stack<Integer> stack;
  10.  
  11. public SortStack(Stack<Integer> stack) {
  12. this.stack=stack;
  13. }
  14.  
  15. /**
  16. * Sorting Subroutine
  17. */
  18. public void sort(){
  19. if(stack.isEmpty())
  20. return;
  21.  
  22. int item=stack.pop();
  23. sort();
  24. compareAndPush(item);
  25. }
  26.  
  27. /**
  28. * Pushing each element of stack by recursion
  29. * @param item: each item of stack which is compared and pushed to stack
  30. */
  31. public void compareAndPush(int item){
  32. if(stack.isEmpty() || item <= stack.peek())
  33. stack.push(item);
  34. else {
  35. int val=stack.pop();
  36. compareAndPush(item);
  37. stack.push(val);
  38. }
  39. }
  40.  
  41.  
  42. public static void main(String[] args) {
  43.  
  44. Stack<Integer> stack= new Stack<Integer>();
  45. stack.push(5);
  46. stack.push(3);
  47. stack.push(1);
  48. stack.push(4);
  49. stack.push(2);
  50. SortStack obj= new SortStack(stack);
  51. obj.sort();
  52.  
  53. System.out.println(stack);
  54. }
  55. }
  56.  
Success #stdin #stdout 0.07s 380224KB
stdin
Standard input is empty
stdout
[5, 4, 3, 2, 1]