Advertisement
YehudaHershoren

sort Queue downwards

Dec 15th, 2017
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.91 KB | None | 0 0
  1. public static void sort(Queue<Integer> q) {
  2.         int max = getMax(q);
  3.        
  4.         Queue<Integer> tmp = new Queue<Integer>();
  5.         Queue<Integer> sort = new Queue<Integer>();
  6.        
  7.         while(!q.isEmpty()) {
  8.             while(!q.isEmpty()) {
  9.                
  10.                 if(q.head() == max) {
  11.                     sort.insert(q.remove());
  12.                 }else {
  13.                     tmp.insert(q.remove());
  14.                 }
  15.                
  16.             }
  17.             while(!tmp.isEmpty()) {
  18.                 q.insert(tmp.remove());;
  19.             }
  20.             if(!q.isEmpty()) {
  21.                 max = getMax(q);
  22.             }
  23.         }
  24.        
  25.        
  26.         while(!sort.isEmpty()) {
  27.             q.insert(sort.remove());
  28.         }
  29.     }
  30.    
  31.     public static int getMax(Queue<Integer> q) {
  32.         Queue<Integer> tmp = new Queue<Integer>();
  33.        
  34.         int max = q.head();
  35.        
  36.         while(!q.isEmpty()) {
  37.             if(q.head() > max) { // change to < for minimum and then the queue will go upwards
  38.                 max = q.head();
  39.             }
  40.             tmp.insert(q.remove());
  41.         }
  42.                
  43.         while(!tmp.isEmpty()) {
  44.             q.insert(tmp.remove());
  45.         }
  46.         return max;
  47.        
  48.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement