Unit 4 (ADS)
Unit 4 (ADS)
Priority Queue
Priority Queue is more specialized data structure than Queue. Like ordinary queue, priority queue has
same method but with a major difference. In Priority queue items are ordered by key value so that
item with the lowest value of key is at front and item with the highest value of key is at rear or vice
versa. So we're assigned priority to item based on its key value. Lower the value, higher the priority.
Following are the principal methods of a Priority Queue.
Basic Operations
Priority Queue is an Abstract Data Type (ADT) that holds a collection of elements, it is similar to a
normal Queue, the difference is that the elements will be dequeued following a priority order.
A real-life example of a priority queue would be a hospital queue where the patient with the most critical
situation would be the first in the queue. In this case, the priority order is the situation of each patient.
Page 1 of 14
ADT — Interface
The Priority Queue interface can be implemented in different ways, is important to have operations to
add an element to the queue and to remove an element from the queue.
# Main operations
enqueue(value, priority) -> Enqueue an element
dequeue() -> Dequeue an element
peek() -> Check the element on the top
isEmpty() -> Check if the queue is empty
Since abstract data types don’t specify an implementation, this means it’s also incorrect to talk about the
ADT — Operations
Traversal : You must be thinking, “how could I print all the elements of a Priority Queue?”
A Priority Queue can be traversed , is possible to navigate in the same way we iterate over a Queue.
queue = PriorityQueue()
queue.enqueue(("Lucas", 1)) # Lucas is added with priority 1
queue.enqueue(("Victor", 4)) # Victor with priority 4
queue.enqueue(("Rafael", 3)) # Rafael with priority 3# PriorityQueue looks like:
# PriorityQueue(("Lucas", 1), ("Rafael", 3), ("Victor", 4))while the is not queue.isEmpty()
print queue.dequeue()# The elements will be printed in this order:
# Lucas -> Rafael -> Victor
This is an abstract operation and the implementation will define how you interact with the Priority
Queue.
Implementation
Page 2 of 14
A Priority Queue can be implemented in different ways, this is my implementation and it’s used to explain
the concepts. The ADT defines what a Priority Queue should be able to do and the Data Structure is its
implementation.
Python — Implementation
This is a simple implementation to show how the priority queue works, a better implementation would
Page 3 of 14
hospital_queue.enqueue
enqueue("Lucas", 1)
hospital_queue.enqueue
enqueue("Rafael", 4)
hospital_queue.enqueue
enqueue("Valentina", 2)
priority_list = []
assert hospital_queue.
hospital_queue.peek() == "Lucas"
while not hospital_queue.
hospital_queue.is_empty():
priority_list.append
append(hospital_queue.dequeue())
# Validate the algorithm checking it is returning the right order
assert priority_list == ["Lucas", "Valentina", "Victor", "Rafael"],
], priority_list
Complexity
# Priority Queue - Time complexity
O(1) -> peek, isEmpty
O(N log N) ->> enqueue, dequeue# Priority Queue - Memory complexity
O(N)
Thus, a max-priority queue returns the element with maximum key first where as, a min-priority
min
queue returns the element with the smallest key first
first.
Page 4 of 14
Priority queues are used in many algorithms like Huffman Codes, Prim's algorithm, etc. It is also used in
scheduling processes for a computer, etc.
Heaps are great for implementing a priority queue because of the largest and smallest element at the
root of the tree for a max-heap and a min-heap respectively. We use a max-heap for a max-priority
queue and a min-heap for a min-priority queue.
2. Extract Maximum/Minimum → To remove and return the maximum and the minimum element from
the max-priority queue and min-priority queue respectively.
Insert
The insert operation inserts a new element in the correct order according to its key. We just insert a
new element at the last of the heap and increase the heap size by 1. Since it is the last element, so we
first give a very large value (infinity) in the case of min-heap and a very less value (-inf) in the case of
max-heap. Then we just change the key of the element by using the Increase/Decrease key operation.
INSERT(A, key)
Page 5 of 14
Doing this, we have disturbed the heap property of the root but we have not touched any of its children,
so they are still heaps. So, we can call Heapify on the root to make the tree a heap again.
EXTRACT-MAXIMUM(A)
MAX-HEAPIFY(A,
HEAPIFY(A, 1) // root is not following max
max-heap property
Page 6 of 14
Binary Search Tree
The binary search tree is an advanced algorithm used for analyzing the node, its left and right branches,
which are modeled in a tree structure and returning the value. The BST is devised on the architecture of
a basic binary search algorithm; hence it enables faster lookups, insertions, and removals of nodes. This
makes the program really fast and accurate.
A. There is the main node or parent level 11. Under it, there are left and right nodes/branches with
their own key values
B. The right sub-tree has key values greater than the parent node
Page 7 of 14
C. The left sub-tree has values than the parent node
The tree always has a root node and further child nodes, whether on the left or right. The algorithm
performs all the operations by comparing values with the root and its further child nodes in the left or
right sub-tree accordingly.
Depends upon the element to be inserted, search, or deleted, after the comparison, the algorithm can
easily drop the left or right subtree of the root node.
BST primarily offers the following three types of operations for your usage:
Each operation has its own structure and method of execution/analysis, but the most complex of all is
the Delete operation.
Search Operation
Always initiate analyzing tree at the root node and then move further to either the right or left subtree
of the root node depending upon the element to be located is either less or greater than the root.
Page 8 of 14
C. Now compare 10 with node 7, 10 > 7, so move to the right-subtree
D. Then compare 10 with the next node, which is 9, 10 > 9, look in the right subtree child
E. 10 matches with the value in the node, 10 = 10, return the value to the user.
A. There is a list of 6 elements that need to be inserted in a BST in order from left to right
B. Insert 12 as the root node and compare next values 7 and 9 for inserting accordingly into the
right and left subtree
C. Compare the remaining values 19, 5, and 10 with the root node 12 and place them accordingly.
19 > 12 place it as the right child of 12, 5 < 12 & 5 < 7, hence place it as left child of 7. Now
compare 10, 10 is < 12 & 10 is > 7 & 10 is > 9, place 10 as right subtree of 9.
Page 9 of 14
Pseudocode for Inserting a Node in BST:
insert (element, root)
Node x = root
Node y = NULL
while x:
y=x
if x.value < element.value
x = x.right
else
x = x.left
if y.value < element
y.right = element
else
y.left = element
Delete Operations
For deleting a node from a BST, there are some cases, i.e. deleting a root or deleting a leaf node. Also,
after deleting a root, we need to think about the root node.
Say we want to delete a leaf node, we can just delete it, but if we want to delete a root, we need to
replace the root’s value with another node. Let’s take the following example:
Case 1- Node with zero children: this is the easiest situation, you just need to delete the node
which has no further children on the right or left.
Case 2 – Node with one child: once you delete the node, simply connect its child node with the
parent node of the deleted value.
Case 3 Node with two children: this is the most difficult situation, and it works on the following
two rules
3a – In Order Predecessor: you need to delete the node with two children and replace it
with the largest value on the left-subtree of the deleted node
3b – In Order Successor: you need to delete the node with two children and replace it with
the largest value on the right-subtree of the deleted node
Page 10 of 14
A. This is the first case of deletion in which you delete a node that has no children. As you can see
in the diagram that 19, 10 and 5 have no children. But we will delete 19.
B. Delete the value 19 and remove the link from the node.
C. View the new structure of the BST without 19
Page 11 of 14
A. This is the second case of deletion in which you delete a node that has 1 child, as you can see in
the diagram that 9 has one child.
B. Delete the node 9 and replace it with its child 10 and add a link from 7 to 10
C. View the new structure of the BST without 9
A. Here you will be deleting the node 12 that has two children
B. The deletion of the node will occur based upon the in order predecessor rule, which means that
the largest element on the left subtree of 12 will replace it.
C. Delete the node 12 and replace it with 10 as it is the largest value on the left subtree
D. View the new structure of the BST after deleting 12
Page 12 of 14
A. 1 Delete a node 12 that has two children
B. 2 The deletion of the node will occur based upon the In Order Successor rule, which means that
the largest element on the right subtree of 12 will replace it
C. 3 Delete the node 12 and replace it with 19 as it is the largest value on the right subtree
D. 4 View the new structure of the BST after deleting 12
Page 13 of 14
# After copying the value of successor to the root #we're deleting the successor
free(newNode)
else
free(y)
Important Terms
Summary
BST is an advanced level algorithm that performs various operations based on the comparison of
node values with the root node.
Any of the points in a parent-child hierarchy represents the node. At least one parent or root
node remains present all the time.
There are a left subtree and right subtree. The left subtree contains values that are less than the
root node. However, the right subtree contains a value that is greater than the root node.
Each node can have either zero, one, or two children.
A binary search tree facilitates primary operations like search, insert, and delete.
Delete being the most complex have multiple cases, for instance, a node with no child, node
with one child, and node with two children.
The algorithm is utilized in real-world solutions like games, autocomplete data, and graphics.
Page 14 of 14