Mahmoud_Hawara

Circular Priority Queue

Dec 19th, 2022
179
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.04 KB | None | 0 0
  1. // Assignment #2
  2.  
  3. public class Solver
  4. {
  5.     public static void main(String args[])
  6.     {
  7.  
  8.         System.out.println();
  9.  
  10.         Circular_priority_queue CPQ = new Circular_priority_queue(5);
  11.  
  12.         CPQ.push(5);
  13.         System.out.printf("-----\nThe Top is: %d\n-----\n", CPQ.top());
  14.         CPQ.push(3);
  15.         System.out.printf("-----\nThe Top is: %d\n-----\n", CPQ.top());
  16.         CPQ.push(5);
  17.         System.out.printf("-----\nThe Top is: %d\n-----\n", CPQ.top());
  18.         CPQ.push(1);
  19.         System.out.printf("-----\nThe Top is: %d\n-----\n", CPQ.top());
  20.         CPQ.pop();
  21.         System.out.printf("-----\nThe Top is: %d\n-----\n", CPQ.top());
  22.  
  23.         System.out.println();
  24.      
  25.     }
  26. }
  27.  
  28. class Circular_priority_queue
  29. {
  30.     int rear, front, MAXSIZE, arr[], nItems;
  31.     Circular_priority_queue(int size)
  32.     {
  33.         MAXSIZE = size;
  34.         rear = -1;
  35.         front = nItems = 0;
  36.         arr = new int[MAXSIZE];
  37.     }
  38.  
  39.     void push(int val)
  40.     {
  41.         if (isFull() == true)
  42.         {
  43.             System.out.println("Sorry, The Queue is Full");
  44.             return;
  45.         }      
  46.        
  47.         int i = rear, cnt = 1;
  48.  
  49.         while (cnt <= nItems && val < arr[i])
  50.         {
  51.             arr[(i + 1) % MAXSIZE] = arr[i];
  52.             i = (i - 1 + MAXSIZE) % MAXSIZE;
  53.             cnt++;
  54.         }
  55.        
  56.         arr[(i + 1) % MAXSIZE] = val;
  57.         rear = (rear + 1) % MAXSIZE;
  58.         nItems++;
  59.     }
  60.  
  61.     int pop()
  62.     {
  63.         if (isEmpty())
  64.         {
  65.             System.out.println("The Queue is Empty");
  66.             return -1;
  67.         }
  68.        
  69.         int temp = arr[front];
  70.         front = (front + 1) % MAXSIZE;
  71.         nItems--;
  72.  
  73.         return temp;
  74.     }
  75.  
  76.     int top()
  77.     {
  78.         if (isEmpty())
  79.         {
  80.             System.out.println("The Queue is Empty");
  81.             return -1;
  82.         }
  83.         return arr[front];
  84.     }
  85.  
  86.     boolean isEmpty()
  87.     {
  88.         return nItems == 0;
  89.     }
  90.  
  91.     boolean isFull()
  92.     {
  93.         return nItems == MAXSIZE;
  94.     }    
  95. }
Advertisement
Add Comment
Please, Sign In to add comment