Advertisement
LoganBlackisle

SortStack

Jun 17th, 2019
117
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. package prep_22_recursion;
  2.  
  3. import java.util.ListIterator;
  4. import java.util.Stack;
  5.  
  6. public class SortAStack {
  7. // Recursive Method to insert an item x in sorted way
  8. public static void sortedInsert(Stack<Integer> s, int x) {
  9. // Base case: Either stack is empty or newly inserted
  10. // item is greater than top (more than all existing)
  11. if (s.isEmpty() || x > s.peek()) {
  12. s.push(x);
  13. return;
  14. }
  15.  
  16. // If top is greater, remove the top item and recur
  17. int temp = s.pop();
  18. sortedInsert(s, x);
  19.  
  20. // Put back the top item removed earlier
  21. s.push(temp);
  22. }
  23.  
  24. // Method to sort stack
  25. public static void sortStack(Stack<Integer> s) {
  26. // If stack is not empty
  27. if (!s.isEmpty()) {
  28. // Remove the top item
  29. int x = s.pop();
  30.  
  31. // Sort remaining stack
  32. sortStack(s);
  33.  
  34. // Push the top item back in sorted stack
  35. sortedInsert(s, x);
  36. }
  37. }
  38.  
  39. // Utility Method to print contents of stack
  40. public static void printStack(Stack<Integer> s) {
  41. ListIterator<Integer> lt = s.listIterator();
  42.  
  43. // forwarding
  44. while (lt.hasNext())
  45. lt.next();
  46.  
  47. // printing from top to bottom
  48. while (lt.hasPrevious())
  49. System.out.print(lt.previous() + " ");
  50. }
  51.  
  52. // Driver method
  53. public static void main(String[] args) {
  54. Stack<Integer> s = new Stack<>();
  55. s.push(30);
  56. s.push(-5);
  57. s.push(18);
  58. s.push(14);
  59. s.push(-3);
  60.  
  61. System.out.println("Stack elements before sorting: ");
  62. printStack(s);
  63.  
  64. sortStack(s);
  65.  
  66. System.out.println(" \n\nStack elements after sorting:");
  67. printStack(s);
  68.  
  69. }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement