Advertisement
sweet1cris

Untitled

Nov 17th, 2017
80
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. public class StackSorting {
  2.     public static void main(String[] args) {
  3.         StackSorting ss = new StackSorting();
  4.         Deque<Integer> stack = new LinkedList<>();
  5.         stack.offerFirst(2);
  6.         stack.offerFirst(1);
  7.         stack.offerFirst(3);
  8.         stack.offerFirst(1);
  9.         stack.offerFirst(3);
  10.         Deque<Integer> helper = ss.stackSorting(stack);
  11.         System.out.println("result top is largest" + Arrays.toString(helper.toArray()));
  12.     }
  13.     // System.out.println("result top is largest" + Arrays.toString(helper.toArray()));
  14.     public Deque<Integer> stackSorting(Deque<Integer> stack) {// stack unsorted
  15.         Deque<Integer> helper = new LinkedList<>(); // helper sorted
  16.         //* int size = stack.size();
  17.         //* int sortedSize = 0;
  18.         int min = Integer.MAX_VALUE;
  19.         int count = 0; // for duplication
  20.         while (!stack.isEmpty()) {
  21.         //* while (sortedsize < size) {
  22.             // stack --> helper find min value
  23.             while (!stack.isEmpty()) {
  24.                 int tmp = stack.pollFirst();
  25.                 min = Math.min(min, tmp);
  26.                 helper.offerFirst(tmp);
  27.             }
  28.             // helper --> stack except the min values
  29.             // 2 1 3 1 3
  30.             while (helper.peekFirst() != null && helper.peekFirst() >= min) {
  31.             // while (helper.size() > sortedSize) {
  32.                 int tmp = helper.pollFirst();
  33.                 if (tmp != min) {
  34.                     stack.offerFirst(tmp);
  35.                 } else {
  36.                     count++;
  37.                 }
  38.             }
  39.             // push min values to helper
  40.             for (int i = 0; i < count; i++) {
  41.                 helper.offerFirst(min);
  42.             }
  43.             // sortedSize = helper.size();
  44.             min = Integer.MAX_VALUE;
  45.             count = 0;
  46.         }
  47.         return helper;
  48.     }
  49. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement