sort numbers with two stacks(many duplicates)

 

 

 

 

 1 public class SortNumbersWithTwoStacks {
 2     Deque<Integer> stack1 = new LinkedList<>();
 3     Deque<Integer> stack2 = new LinkedList<>();
 4 
 5 
 6     public SortNumbersWithTwoStacks() {
 7         stack1.push(1);
 8         stack1.push(2);
 9         stack1.push(4);
10         stack1.push(1);
11         stack1.push(2);
12         stack1.push(1);
13         stack1.push(3);
14         stack1.push(2);
15     }
16     /*
17     * stack1: sorted|unsorted
18     * stack2: buffer place
19     * globalMin: current iteration smallest value
20     * counter: how many times in the current iteration the globalMin shows
21     * */
22     private void sort(){
23         int globalMin = Integer.MAX_VALUE ;
24         int itemsToSort = stack1.size() ;
25         //counter for # of same items as globalMin
26         int counter = 0 ;
27         for (int i = 0; i < itemsToSort ;) {
28             //for every sort, globalMin = top item of stack1; also reset the counter = 1
29             counter = 1 ;
30             globalMin = stack1.pop() ;
31             while (!stack1.isEmpty()){
32                 int value = stack1.pop() ;
33                 if (value<globalMin){
34                     for (int j = counter; j >0 ; j--) {
35                         stack2.push(globalMin);
36                     }
37                     counter = 1 ;
38                     globalMin = value ;
39                 } else if(value == globalMin){
40                     counter++ ;
41                 } else{
42                     stack2.push(value);
43                 }
44             }
45             //now add back globalMin
46             for (int j = counter; j >0 ; j--) {
47                 stack1.push(globalMin);
48                 /*
49                 this is to make sure no dupl add. make sure the outside loop doesnt have i++
50                 otherwise will jump over one
51                 * */
52                 i++;
53             }
54             //and then add back stack2
55             while (!stack2.isEmpty()){
56                 stack1.push(stack2.pop());
57             }
58         }
59     }
60 
61     public static void main(String[] args) {
62         SortNumbersWithTwoStacks sort = new SortNumbersWithTwoStacks();
63         sort.sort();
64         while (!sort.stack1.isEmpty()) {
65             System.out.println(sort.stack1.pop());
66         }
67     }
68 }

 

 

 

TEST:

 

posted @ 2018-03-19 02:24  davidnyc  阅读(290)  评论(0编辑  收藏  举报