0% found this document useful (0 votes)
11 views16 pages

Dsa Ass 1 Ruba

The document discusses priority queues, including their types, representation, operations, and applications. Priority queues are a special type of queue that orders elements based on priority, with higher priority elements being served first. They can be implemented using arrays, linked lists, heaps, or binary search trees, with heaps providing the most efficient implementation.

Uploaded by

rubafaraz56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views16 pages

Dsa Ass 1 Ruba

The document discusses priority queues, including their types, representation, operations, and applications. Priority queues are a special type of queue that orders elements based on priority, with higher priority elements being served first. They can be implemented using arrays, linked lists, heaps, or binary search trees, with heaps providing the most efficient implementation.

Uploaded by

rubafaraz56
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Comsats University Islamabad

Abbottabad Campus

ASSIGNMENT NO 1

SUBBMITTED BY: RUBA FARAZ


SUBMITTED TO: dr Imran Ali
SUBJECT: DSA
____QUESTION NO 1____
Define priority queue concepts its types, application, algorithm and full implementation code

Priority Queue
A priority queue is a special type of queue in which each element is associated
with a priority value. And, elements are served on the basis of their priority. That
is, higher priority elements are served first.
However, if elements with the same priority occur, they are served according to
their order in the queue.
Assigning Priority Value
Generally, the value of the element itself is considered for assigning the priority.
For example,
The element with the highest value is considered the highest priority element.
However, in other cases, we can assume the element with the lowest value as the
highest priority element.
We can also set priorities according
Difference between Priority Queue and Normal Queue
In a queue, the first-in-first-out rule is implemented whereas, in a
priority queue, the values are removed on the basis of priority. The
element with the highest priority is removed first.

Representation of priority queue


We will learn how to use a one-way list to represent a priority queue. A priority
queue is a special kind of list that keeps track of the importance of each item. We
will create this priority queue using a list that has three parts:

 INFO: This part stores the actual data.


 PRN: This part stores the priority number of each piece of data. This number
shows how important each piece of data is.
 LINK: This part stores the address of the next item in the list.

By using these three parts, we can create a priority queue that can efficiently store
and retrieve data based on its importance.

Implementation of Priority Queue


Priority queue can be implemented using an array, a linked list, a heap
data structure, or a binary search tree. Among these data structures, heap
data structure provides an efficient implementation of priority queues.
A comparative analysis of different implementations of priority queue is
given below.

Operations peek insert delete

Linked List O(1) O(n) O(1)

Binary Heap O(1) O(log n) O(log n)

Binary Search Tree O(1) O(log n) O(log n)

Priority Queue Operations


Basic operations of a priority queue are inserting, removing, and peeking
elements.

1. Inserting an Element into the Priority Queue


Inserting an element into a priority queue (max-heap) is done by the
following steps.

ALGORITHM FOR PRIORITY QUEUE INSERTION:

Algorithm PQ Insert (PQ, N, item, priority, Front, Rear)

[This algorithm is used to insert an element into the Priority Queue, where

PQ = Array

N = Final Limit

Item = element to be inserted

Priority = priority of the element

Front, Rear = pointers]


Step-1 [Check for overflow]

If ((Front = 1) && (Rear = N) or (Front = Rear + 1)) then

Write (“Overflow”)

Goto step-5

End if

Step-2 [Find the correct position]

I ← Rear

While (I > 0) && (PQ[I].priority

I←I-1

End while

Step-3 [Shift elements]

If (I

For J ← Rear to I + 1 do

PQ[J + 1] ← PQ[J]

End for

End if

Step-4 [Insert the element]

PQ[I + 1].item ← item

PQ[I + 1].priority ← priority

Rear ← Rear + 1

Step-5 [Finished]

Exit
 Insert the new element at the end of the tree.

Insert an element at the end of the


queue

 Heapify the tree. Heapify after


insertion

2. Deleting an Element from the Priority Queue

Deleting an element from a priority queue (max-heap) is done as follows:


ALGORITHM FOR PRIORITY QUEUE deletion:

Algorithm PQ Delete (PQ, N, Front, Rear)

[This algorithm is used to delete an element from the Priority Queue, where

PQ = Array

N = Final Limit

Front, Rear = pointers]

Step-1 [Check for underflow]

If ((Front = 1) && (Rear = 0) or (Front = Rear + 1)) then

Write (“Underflow”)

Goto step-4

End if

Step-2 [Delete the element]

Item ← PQ [Front].item

Priority ← PQ [Front].priority

Step-3 [Shift elements]

For I ← Front to Rear - 1 do

PQ [I] ← PQ[I + 1]

End for

Step-4 [Finished]
Exit
 Select the element to be deleted.
Select the element to be deleted

 Swap it with the last element. Swap


with the last leaf node element

 Remove the last element. Remove


the last element leaf
 Heapify the tree. Heapify the
priority queue

.3 Peeking from the Priority Queue (Find max/min)3


Peek operation returns the maximum element from Max Heap or
minimum element from Min Heap without deleting the node.
For both Max heap and Min Heap
Types of Priority Queue:

1) Ascending Order Priority Queue


In ascending order priority queue, the element with a lower priority value is given
a higher priority in the priority list .
2) Descending order Priority Queue
The root node is the maximum element in a max heap. It will also remove the
element with the highest priority first. As a result, the root node is removed from
the queue. This deletion leaves an empty space, which will be filled with fresh
insertions in the future. The heap invariant is then maintained by comparing the
newly inserted element to all other entries in the queue.

4. Extract-Max/Min from the Priority Queue


Extract-Max returns the node with maximum value after removing it from
a Max Heap whereas Extract-Min returns the node with minimum value
after removing it from Min Heap.

Types of Queues:
Simple Queue:
The basic form of a queue that follows the FIFO principle. Elements are
added to the rear and removed from the front.
Circular Queue:
A queue where the last element is connected to the first element, creating
a circular structure. This type of queue efficiently utilizes memory and
allows for constant-time enqueue and dequeue operations.
Priority Queue:
A queue where elements are served based on their priority levels. Higher-
priority elements are processed before lower-priority ones, regardless of
their arrival order .
Double-ended Queue (Deque):
A queue that allows insertion and deletion of elements at both the front
and the back. This provides more flexibility in managing the queue.
Blocking Queue:
A queue that blocks or waits when attempting to enqueue an element into
a full queue or dequeue from an empty queue. This queue type is often
used in concurrent programming to coordinate between producer and
consumer threads .

Applications of Queues:
Operating Systems:
Queues are used in operating systems for job scheduling, process
scheduling, and managing interrupts .
Networking:
In network routers, queues are used to manage packets waiting for
transmission, ensuring efficient data flow.
Breadth-First Search (BFS):
Queues are essential in graph algorithms like BFS for traversing graphs
in a level-by-level manner.

Printer Queue:
Managing documents waiting to be printed, ensuring fair and orderly
printing.
Banks and Supermarkets:
Queues are utilized to manage customer queues at service points,
ensuring fairness and efficiency in serving customers.
Call Center Systems:
Managing incoming calls waiting to be serviced by agents, ensuring
timely and orderly handling of customer inquiries.
Simulation:
Queues are used in simulations to model various real-world scenarios
such as traffic flow, customer service systems, and manufacturing
processes.
Buffering :
In computing and networking, queues are used for buffering data between
different processes or systems, ensuring smooth data transmission and
processing. Priority Queue Implementations in, Java.
Advantages of Priority Queue:
 It helps to access the elements in a faster way. This is because elements in a
priority queue are ordered by priority, one can easily retrieve the highest
priority element without having to search through the entire queue.
 The ordering of elements in a Priority Queue is done dynamically. Elements in
a priority queue can have their priority values updated, which allows the queue
to dynamically reorder itself as priorities change.
 Efficient algorithms can be implemented. Priority queues are used in many
algorithms to improve their efficiency, such as Dijkstra’s algorithm for finding
the shortest path in a graph and the A* search algorithm for path finding.
Disadvantages of Priority Queue:
 High complexity. Priority queues are more complex than simple data
structures like arrays and linked lists, and may be more difficult to implement
and maintain.
 High consumption of memory. Storing the priority value for each element in a
priority queue can take up additional memory, which may be a concern in
systems with limited resources.
 It is not always the most efficient data structure. In some cases, other data
structures like heaps or binary search trees may be more efficient for certain
operations, such as finding the minimum or maximum element in the queue.
 At times it is less predictable. This is because the order of elements in a
priority queue is determined by their priority values, the order in which
elements are retrieved may be less predictable than with other data structures
like stacks or queues, which follow a first-in, first-out (FIFO) or last-in, first-
out (LIFO) order.

----------PROGRAM-------

public class PriorityQueue

private int[] array;

private int size;

public PriorityQueue(int capacity)

array = new int[capacity];

size = 0; }

public void insert(int item, int priority)

if (size >= array.length) {

System.out.println("Queue is full!");
return;

array[size] = item;

int i = size;

while (i > 0 && array[i - 1] < priority)

swap(array, i, i - 1);

i--; }

size++; }

public int extractMax() {

if (size == 0) {

System.out.println("Queue is empty!");

return -1; }

int max = array[0];

array[0] = array[size - 1];

size--;

heapifyDown(0);

return max; }

public int extractMin()

if (size == 0)

System.out.println("Queue is empty!");
return -1; }

int min = array[0];

array[0] = array[size - 1];

size--;

heapifyUp(0);

return min; }

private void heapifyDown(int i) {

int largest = i;

int left = 2 * i + 1;

int right = 2 * i + 2;

if (left < size && array[left] > array[largest]) {

largest = left; }

if (right < size && array[right] > array[largest]) {

largest = right; }

if (largest != i) {

swap(array, i, largest);

heapifyDown(largest);

}}

private void heapifyUp(int i) {

int smallest = i;

int parent = (i - 1) / 2;

if (parent >= 0 && array[parent] < array[smallest]) {

smallest = parent; }
if (smallest != i) {

swap(array, i, smallest);

heapifyUp(smallest);

}}

private void swap(int[] array, int i, int j) {

int temp = array[i];

array[i] = array[j];

array[j] = temp;

}}

____________________________________________________________________________

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy