crsandu

Untitled

Feb 5th, 2019
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.83 KB | None | 0 0
  1. public class PriorityQueue <Type extends Comparable>{
  2.     private int size = 0;
  3.     private int currentPos = 0;
  4.     private Type array[] = null;
  5.    
  6.     public PriorityQueue(int size) {
  7.         this.array = (Type[]) new Object[size];
  8.         this.size = size;
  9.     }
  10.    
  11.     public PriorityQueue() {
  12.         this(50); // default size
  13.     }
  14.    
  15.     private void bubbleUp(int pos) {
  16.         int parent = pos/2;
  17.        
  18.         if(array[pos].compareTo(array[parent]) == -1) {
  19.             // parintele e mai mare decat fiul
  20.             // le schimbam pozitia
  21.            
  22.             Type aux = array[parent];
  23.             array[parent] = array[pos];
  24.             array[pos] = aux;
  25.            
  26.             this.bubbleUp(parent);
  27.         }
  28.     }
  29.    
  30.     public void addElements(Type newElm) throws Exception {
  31.         if(this.currentPos == this.size) {
  32.             throw new Exception();
  33.         }
  34.         else {
  35.             this.array[++this.currentPos] = newElm;
  36.             this.bubbleUp(this.currentPos);
  37.         }
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment