0% found this document useful (0 votes)
8 views14 pages

Unit 4 (ADS)

The document discusses the concept of Priority Queues, an abstract data type that organizes elements based on priority, with operations for inserting and removing elements. It also covers the implementation of Priority Queues using heaps, detailing the time complexity for various operations. Additionally, it introduces Binary Search Trees (BST), explaining their structure, operations for searching, inserting, and deleting nodes, along with relevant pseudocode.

Uploaded by

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

Unit 4 (ADS)

The document discusses the concept of Priority Queues, an abstract data type that organizes elements based on priority, with operations for inserting and removing elements. It also covers the implementation of Priority Queues using heaps, detailing the time complexity for various operations. Additionally, it introduces Binary Search Trees (BST), explaining their structure, operations for searching, inserting, and deleting nodes, along with relevant pseudocode.

Uploaded by

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

UNIT 4(ADS) for new topic search with 

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

 insert / enqueue − add an item to the rear of the queue.


 remove / dequeue − remove an item from the front of the queue.

Priority Queue Representation

Priority Queue — Abstract Data Type

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

time complexity of a given abstract data type.

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.

Priority Queue — Data Structure

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

use a Heap data structure to solve this problem.


class
PriorityQueue:
"""
This priority queue uses a given number as priority order.
The smallest number has the higher priority
"""
def __init__(self):
self.queue = []
def enqueue(self, value: str, priority: int) -> None:
"""Add the value the queue based on its priority"""
self.queue.append((value, priority))
self.queue = reorder_queue(self.queue)
def dequeue(self) -> str:
"""Dequeue the first value from the queue"""
# Swap elements and reorder_queue
firstElement, lastElement = self.queue[0], self.queue[-1]
self.queue[0], self.queue[-1] = lastElement, firstElement
value, priority = self.queue.pop()
self.queue = reorder_queue(self.queue)
return value
def is_empty(self) -> bool:
return len(self.queue) == 0
def peek(self) -> str:
"""Show the first value from the queue"""
return self.queue[0][0]
def reorder_queue(queue):
return sorted(queue, key=lambda v: v[1])
if __name__ == '__main__':
hospital_queue = PriorityQueue()
hospital_queue.enqueue("Victor", 3)

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)

Realizing a Priority Queue Using Heaps, Definition, Insertion, Deletion


Priority queue is a type of queue in which every element has a key associated to it and the queue
returns the element according to these keys, unlike the traditional queue which works on first come first
serve basis.

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.

1. Insert → To insert a new element in the 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)

heap_size = heap_size+1 // increasing heap size by 1

A[heap_size] = -infinity // making last element very less

INCREASE-KEY(A, heap_size, key) // chaning key of last element


All the steps are constant time taking steps, except the Increase/Decrease key. So it will also
take O(lgn)O(lg n) time.

Extract Maximum/Minimum (DELETE)


This is like the pop of a queue, we return the element as well as delete it from the heap. So, we have to
return and delete the root of a heap. Firstly, we store the value of the root in a variable to return it later
from the function and then we just make the root equal to the last element of the heap. Now the root is
equal to the last element of the heap, we delete the last element easily by reducing the size of the heap
by 1.

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 = A[1] // stroing maximum value

A[1] = A[heap_size] // making root equal to the last element

heap_size = heap_size-11 // delete last element

MAX-HEAPIFY(A,
HEAPIFY(A, 1) // root is not following max
max-heap property

return max //returning the maximum value


All the steps are constant time taking process except the Heapify operation, it will
take O(lgn)O(lg n) time and thus the Extract Maximum/Minimum is going to take O(lgn)O(lg n) time.

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.

Attributes of Binary Search Tree


A BST is made of multiple nodes and consists of the following attributes:

 Nodes of the tree are represented in a parent-child relationship


 Each parent node can have zero child nodes or a maximum of two subnodes or subtrees on the
left and right sides.
 Every sub-tree, also known as a binary search tree, has sub-branches on the right and left of
themselves.
 All the nodes are linked with key-value pairs.
 The keys of the nodes present on the left subtree are smaller than the keys of their parent node
 Similarly, The left subtree nodes’ keys have lesser values than their parent node’s keys.

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:

 Search: searches the element from the binary tree


 Insert: adds an element to the binary tree
 Delete: delete the element from a binary tree

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.

A. The element to be searched is 10


B. Compare the element with the root node 12, 10 < 12, hence you move to the left subtree. No
need to analyze the right-subtree

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.

Pseudo Code for Searching in BST:


search(element, root)
if !root
return -1
if root.value == element
return 1
if root.value < element
search(element, root.right)
else
search(element, root.left)
Insert Operation
This is a very straight forward operation. First, the root node is inserted, then the next value is compared
with the root node. If the value is greater than root, it is added to the right subtree, and if it is lesser
than the root, it is added to the left subtree.

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

Pseudo Code for Deleting a Node:


delete (value, root):
Node x = root
Node y = NULL
# searching the node
while x:
y=x
if x.value < value
x = x.right
else if x.value > value
x = x.left
else if value == x
break
# if the node is not null, then replace it with successor
if y.left or y.right:
newNode = GetInOrderSuccessor(y)
root.value = newNode.value

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

 Insert: Inserts an element in a tree/create a tree.


 Search: Searches an element in a tree.
 Preorder Traversal: Traverses a tree in a pre-order manner.
 Inorder Traversal: Traverses a tree in an in-order manner.
 Postorder Traversal: Traverses a tree in a post-order manner.

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

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