From 72317205b91bbcf9fbc4eba9e0a1dd0406fa6947 Mon Sep 17 00:00:00 2001 From: Muhammed Sabah Date: Thu, 14 Oct 2021 18:21:33 +0530 Subject: [PATCH] chore(Java): add priority queue array (#575) --- algorithms/Java/README.md | 1 + .../Java/queues/priority-queue-array.java | 78 +++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 algorithms/Java/queues/priority-queue-array.java diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 1a59a07d..b2b02385 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -27,6 +27,7 @@ ## Queues - [Circular Queue using Linked List](queues/circular-queue-linked-list.java) - [Queue using Linked List](queues/queue-linked-list.java) +- [Priority Queue using Array](queues/priority-queue-array.java) ## Scheduling - [Multi-Level Queue Scheduling](scheduling/multi-level-queue-scheduling.java) diff --git a/algorithms/Java/queues/priority-queue-array.java b/algorithms/Java/queues/priority-queue-array.java new file mode 100644 index 00000000..6ea9a219 --- /dev/null +++ b/algorithms/Java/queues/priority-queue-array.java @@ -0,0 +1,78 @@ +// Class implementation of Priority-Queue using an array + +import java.util.*; + + +class PriorityQueue { + private int max_size; // To provide maximum size of Array + private int[] arr; + private int no_items; + + public PriorityQueue(int s){ + max_size = s; + arr = new int[max_size]; + no_items = 0; + } + + public void insert(int val){ //Method to insert element into Priority Queue + + int j; + if (no_items == 0){ + arr[no_items++] = val; + } + else { + + for ( j=no_items-1;j>=0;j--){ + + if (val' operator + { + arr[j+1] = arr[j]; + } + else break; + + } + + arr[j+1] = val; + no_items++; + } + + } + public void remove(){ // Method to remove front element in Priority Queue + --no_items; + } + + public int front(){ // Method to retrieve front element + return arr[no_items-1]; + } + + public boolean isEmpty() { // Method to check if queue is empty + return no_items == 0; + } + public boolean isFull() { // Method to check if queue is full + return no_items == max_size; + } + + +} + +class Main { // Class containing main method. + + public static void main(String[] args) { + PriorityQueue pq = new PriorityQueue(5); + pq.insert(23); // [23] + pq.insert(56); // [56,23] + pq.insert(25); // [56,25,23] + System.out.println(pq.front()); // 56 + pq.remove(); // [25,23] + System.out.println(pq.front()); // 25 + System.out.println(pq.isEmpty()); // False + pq.insert(100); // [100,25,23] + pq.insert(98); // [100,98,25,23] + pq.insert(99); // [100,99,98,25,23] + System.out.println(pq.front()); // 100 + System.out.println(pq.isFull()); // True + + + } + +}