0% found this document useful (0 votes)
27 views18 pages

DS U (1+3+5) Slips

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)
27 views18 pages

DS U (1+3+5) Slips

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/ 18

(U3)QUEUE:

Queue is a linear data structure in which


elements can be inserted from one end called
rear and deleted from other end called front.
● The deletion or insertion of elements can take place only at the front or rear end called
dequeue and enqueue respectively. The first element that gets added into the queue is
the first one to get removed from the queue. Hence the queue is referred to as First-In-
First-Out list (FIFO).
Operations performed on Queue:
There are two possible operations performed on a queue. They are
enqueue: Allows inserting an element at the rear of the queue.
dequeue: Allows removing an element from the front of the queue.

REPRESENTATION OF QUEUEs:
ARRAYs: Queues can be easily
represented using linear arrays. Every
queue has front and rear variables that
point to the position from where deletions
and insertions can be done, respectively.
The array representation of a queue is
shown
Drawback: The array must be declared to
have some fixed size. If we allocate space

linked list :-
* In a linked queue, every element has two parts, one that stores the
data and another that
stores the address of the next element.
* The START pointer of the linked list is used as FRONT. Here, we will
also use another
pointer called REAR, which will store the address of the last element in
the queue. All
insertions will be done at the rear end and all the deletions will be done
at the front end.
* If FRONT = REAR = NULL, then it indicates that the queue is empty.

www.Jntufastupdates.com 1
(U3)IMPLEMENTATIONOF QUEUEs: Using Arrays:
Algorithm for ENQUEUE operation
1. Check whether queue is FULL. (rear >= SIZE-1)
2. If it is FULL, then display an error message "Queue
is FULL!!! Insertion is not
possible!!!" and terminate the function.
3. If it is NOT FULL, then increment rear value by one
(rear++) and
set queue[rear] = value.
Algorithm for DEQUEUE operation
1. Check whether queue is EMPTY. (front == -1)
2. If it is EMPTY, then display "Queue is EMPTY!!!
Deletion is not possible!!!" and
terminate the function.
3. If it is NOT EMPTY, then display queue[front] as
deleted element, increment
the front value by one (front ++). If we are deleting
last element both front and rear are
equal (front == rear), then set both front and rear
to '-1' (front = rear = -1).
Let us consider a queue, which can hold
maximum of five elements.
Initially the queue is empty. An element can be
added to the queue only at the rear end of the
queue.
Before adding an element in the queue, it is
checked whether queue is full. If the queue is
full, then addition cannot take place. Otherwise,
the element is added to the end of the list at
the
rear
end. If
we are inserting first element into the queue
then
change front to 0 (Zero).
Now, delete an element 1. The element
deleted is the element at the front of the
queue. So the status of the queue is:
When the last element delete 5. The
element deleted at the front of the queue. So
the
status of the queue is empty. So change the
values of front and rear to -1 (front=rear= -1)
The dequeue operation deletes the element from
the front of the queue. Before
deleting and element, it is checked if the queue
is empty. If not the element pointed by front is
deleted from the queue and front is now made
to point to the next element in the queue.
Drawback: If we implement the queue using an
array, we need to specify the array size
at the beginning (at compile time). We can't
change the size of an array at runtime. So,
the queue will only work for a fixed number of
elements. www.Jntufastupdates.com 3
(U3) Implementation of queue
using linked list
In a linked queue, each node of the queue
consists of two parts i.e. data part and theEach
element of the queue points to its
immediate next element in the memory.
In the linked queue, there are two pointers
maintained in the memory i.e. front pointer and
rear
pointer. The front pointer contains the
address of the starting element of the
queue while the rear pointer contains the address
of the last element of the queue.

struct node *front = NULL, *rear = NULL;


Operation on Linked Queue: There are two basic operations which can be implemented on the
linked queues. The operations are Enqueue and Dequeue.
Enqueue function: Enqueue function will add the element at the end of the linked list.
1. Declare a new node and allocate memory for it.

2. If front == NULL, make both front and rear points to the new node.

3. Otherwise, add the new node in rear->next (end of the list) and make the new node
as the rear node. i.e. rear = new node

Dequeue function: Dequeue function will remove the first element from the queue.

www.Jntufastupdates.com 4
(U3)CIRCULAR QUEUEs:
In a Linear queue, once the queue is completely full, it's not possible to insert any more
elements. When we dequeue any element to remove it from the queue, we are actually
moving the front of the queue forward, but rear is still pointing to the last element of
the queue, we cannot insert new elements.
Circular Queue is also a linear data structure, which follows the principle of FIFO(First
In First Out), but instead of ending the queue at the last position, it again starts from the
first position after the last, hence making the queue behave like a circular data structure.

Operations on Circular Queue: The following are the operations that can be performed
o enQueue(value): This function is used to insert the new value in the Queue. The new
element is always inserted from the rear end.
o deQueue(): This function deletes an element from the Queue. The deletion in a Queue
always takes place from the front end.
Enqueue operation: The steps of enqueue operation are given below:
o First, we will check whether the Queue is full or not.
o Initially the front and rear are set to -1. When we insert the first element in a Queue, front
and rear both are set to 0.
o From 2nd element onwards, When we insert a new element, the rear gets incremented,

i.e., rear=rear+1.
Queue is not full:
o If rear != max - 1, then rear will be incremented and the new value will be inserted at the
rear end of the queue.
o If front != 0 and rear = max - 1, it means that queue is not full, then set the value of rear
to 0 and insert the new element there.
Queue is full:
o When front ==0 && rear = max-1, which means that front is at the first position of the
Queue and rear is at the last position of the Queue.
o front== rear + 1;

www.Jntufastupdates.com 5
(U3) Applications of Queue:
1. Queues are widely used as waiting lists for a single shared resource like printer, disk, CPU.
2. Queues are used to transfer data asynchronously between two processes
3. Queues are used as buffers on MP3 players and portable CD players, iPod playlist.
4. Queues are used in Playlist for jukebox to add songs to the end, play from the front.
5. Queues are used in operating system for handling interrupts. The interrupts are handled in

the same order as they arrive i.e First come first served.

Applications of Stacks

Stack is used to reversing the given


string.
Stack is used to evaluate a postfix
expression.
Stack is used to convert an infix
expression into postfix/prefix form.
Stack is used to matching the
parentheses in an expression.

www.Jntufastupdates.com 6
(U3)DEQUE:
Deque or Double Ended Queue is a
type of queue in which insertion and
removal of elements can be performed
from either from the front or rear.
Thus, it does not follow FIFO rule
(First In First Out).

Types of Deque:
1. Input Restricted Deque: In this deque, input is restricted at a single end but allows deletion
at both the ends.
2. Output Restricted Deque: In this deque, output is restricted at a single end but allows
insertion at both the ends.

Operations on a Deque
 Initially take an array (deque) of size n. and Set two pointers at the first position and
set front = -1 and rear = -1.
1. Insert at the Front: This operation adds an element at the front.
 Check the position of front, If front < 1, we can’t add elements in the front end.
Otherwise decrement the front and at front location we can insert the element.
2. Insert at the Rear: This operation adds an element to the rear.
 Check if the array is full. Then the queue is overflow. Otherwise, reinitialize rear = 0
& front=0 for the first insertion, Else, increase rear by 1.and at rear location we can
insert the element.
3. Delete from the Front: The operation deletes an element from the front.
 Check If the deque is empty (i.e. front = -1), deletion cannot be performed (underflow
condition). If the deque has only one element (i.e. front = rear), set front = -1 and
rear = -1. Else, front = front + 1.
4. Delete from the Rear: This operation deletes an element from the rear.
 If the deque is empty (i.e. front = -1), deletion cannot be performed (underflow
condition). If the deque has only one element (i.e. front = rear), set front = -1 and
rear = -1. Else, rear = rear - 1.

www.Jntufastupdates.com 7
:-
(U3) Priority Queue:-
 A priority queue is a data structure in which each element is assigned a priority. The
::
priority of the element will be used to determine the order in which the elements will be
processed.
 The general rules of processing the elements of a priority queue are
o An element with higher priority is processed before an element with a lower priority.
o Two elements with the same priority are processed on a first-come-first-served (FCFS)
basis.
Array Representation of a Priority Queue:
 When arrays are used to implement a priority queue, then a separate queue for each
priority number is maintained. Each of these queues will be implemented using circular
arrays or circular queues. Every individual queue will have its own FRONT and REAR
pointers.
 We use a two-dimensional array for this purpose where each queue will be allocated the
same amount of space.
 FRONT[P] and REAR[P] contain the front and rear values of row P, where P is the priority
number.

Insertion: Deletion:
To insert a new element with priority
Pin the priority queue, add the To delete an element, we find the first
element at the rear endof row P, nonemptyqueue and then process the
where Pis the row number as well as frontelement ofthe first non-empty
thepriority number of that element. queue.
For example, if wehave to insert an In our priority queue, thefirst non-
element Xwith priority number 2,then
empty queue is the one with priority
the priority queue will be given as
shown in Fig. number6and the front element is K, so
Kwill be deleted andprocessed first.

www.Jntufastupdates.com 8
(U3) Multiple Queues:-

:-
 When we implement a queue using an array, the size of the array must be known in advance.
::
If the queue is allocated less space, then frequent overflow conditions will be encountered.
To deal with this problem, the code will have to be modified to reallocate more space for
the array.
 In case we allocate a large amount of space for the queue, it will result in sheer wastage of
the memory. So a better solution to deal with this problem is to have multiple queues or to
have more than one queue in the same array of sufficient size.
 An array Queue[n] is used to represent two queues, Queue A and Queue B. The value of n
is such that the combined size of both the queues will never exceed n. While operating on
these queues, it is important to note one thing—queue A will grow from left to right,
whereas queue B will grow from right to left at the same time.
Example:

fB=rB=SIZE. Because initially QA and QB are empty.


 For the first insertion in QA, the values of fA=rA=0. Similarly for QB, the values are
fB=rB=SIZE-1.
 From the second insertion onwards we can increment only the rear pointer rA for QA and
decrement the rear rB for QB.
 Delete the elements from queue only at front end. In QA, the elements can delete from fA,
if you delete the element then increment fA. In QB, the elements can delete from fB, if you
delete the element then decrement fB.
 When the condition rA=rB-1 or rA+1=rB meets then the entire queue is full. If you try to
insert the element in either of queues it says that QUEUE is OVERFLOW.

www.Jntufastupdates.com 9
Stack:-
(U3)● Stack is a linear data structure in which insertion and
deletion can perform at the same end called top of stack.
:- an item is added to a stack, the operation is called
● When
:: and when an item is removed from the stack the
push,
operation is called pop.

● Stack is also called as Last-In-First-Out (LIFO) list which


means that the last element that is inserted will be the first
element to be removed from the stack.
● When a stack is completely full, it is said to be Stack is Overflow and if stack is completely
empty, it is said to be Stack is Underflow.
Array Representation of Stacks:
 Every stack has a variable called TOP associated with it, which is used to pointing the
topmost element of the stack. It is this position where the element will be inserted to or
deleted from.
 There is another variable called MAX, which is used to store the maximum number of
elements that the stack can hold.
 If TOP = NULL, then it indicates that the stack is empty and if TOP = MAX–1, then the
stack is full.

Linked Representation of Stacks:

The drawback in that the array must be declared to have some


fixed size. In case the stack is a very small one or its maximum
size is known in advance
In a linked stack, every node has two parts, one that stores
dataand another that stores the addressof the next node. The
START pointer of the linked list is used as TOP.
All insertions and deletions are done at the TOP(similar to
insertion at beginning).
If TOP = NULL, then it indicates that the stack is empty.
The linked representation of a stack is

www.Jntufastupdates.com 10
(U3) Array implementation of stack
The basic operations performed in a stack :-
1) push(x) : add element x at top of stack
2)pop() :- remove top element from stack
3)peek() :- get top element of stack without
removing it

Algorithm for POP operation


1. Check if the stack is empty or not.

2. If the stack is empty, then print error of


underflow and exit the program.

3. If the stack is not empty, then print the element


at the top and decrement the top.

Algorithm for PEEK operation

1. Check if the stack is empty or not.


2. If the stack is empty, then print error of underflow and exit the program.
3. If the stack is not empty, then print the element at the top without removing it.

www.Jntufastupdates.com 11
(U3) Linked Implementation of Stack:
 In a linked stack, each node of the stack consists of two parts i.e. data part and the next part.
Each element of the stack points to its immediate next element in the memory.
 In the linked stack, there one pointer maintained in the
memory i.e. TOP pointer. The TOP pointer contains the
address of the starting element of the STACK.
 Both Insertion and deletions are performed at only one end
called TOP. If TOP is NULL, it indicates that the stack is empty. Initially

struct node *TOP = NULL ;

Operation on Linked STACK: There are two basic operations


which can be implemented on the
linked queues. The operations are PUSH and POP.
PUSH function: PUSH function will add the element at the beginning of the linked list.

1. Declare a new node and allocate memory for it.


2. If TOP == NULL, make TOP points to the new node.
3. Otherwise, add the new node at TOP end and makes the next of new node is previous TOP.

POP function: POP function will remove the TOP element from the STACK.
1. Check whether the stack is empty or not
2. If it is the stack is empty (TOP == NULL), We can't POP the element.
3. Otherwise, Make the TOP node points to the next node. i.e TOP = TOP->next; Free the
TOP node's memory.

www.Jntufastupdates.com 12
(U1)Classification of data structures and applications
Data structures can be broadly classified into 5. Trees:
the following categories based on their Trees are hierarchical data structures with a root
organization and usage: node and child nodes. They offer efficient
1. Arrays: searching, insertion, and deletion operations.
Arrays are a collection of elements stored in Common types include binary trees, AVL trees,
contiguous memory locations, accessed using and B-trees.
indices. They provide constant time access to applications of Trees :
elements but have fixed sizes. They are - File system organization: Trees are used to
commonly used for implementing lists, matrices, represent file directories in real-time systems.
and dynamic programming algorithms. - Network routing: Trees help efficiently route
applications of Array: data packets in networks.
- Image processing: Arrays are used to 6. Graphs:
represent pixel data in images for efficient Graphs consist of nodes connected by edges and
manipulation. can be directed or undirected. They are used for
- Signal processing: Arrays are employed to modeling complex relationships and solving various
process and analyze time-series data. problems like shortest path, network flow, and
2. Linked Lists: social network analysis.
Linked lists consist of nodes, each containing applications of graphs:
data and a reference to the next node. They - GPS navigation: Graphs are used to find the
allow dynamic memory allocation, easy insertion shortest routes between locations.
and deletion, but have slower access times - Disaster management: Graphs aid in identifying
compared to arrays. critical infrastructure nodes during emergencies
Real-time applications:

(U5) Application of
- Task scheduling: Linked lists can be used to
manage real-time tasks with varying priorities.

graph
- Memory management: Linked lists can help
efficiently manage memory in real-time systems
3. Stacks:
Stacks follow the Last-In-First-Out (LIFO) 1. **Social Networks**: Social media platforms
principle, where the last element inserted is the like Facebook, Twitter, and LinkedIn utilize
first one to be removed. They have limited graphs to represent connections between users.
access points and are commonly used to Nodes represent individuals, and edges
implement function calls, expression evaluation, represent friendships, follow relationships, or
and backtracking algorithms. professional connections.
2. **Transportation Networks**: Graphs are used
applications of stack:
to model transportation systems, such as road
- Real-time operating systems: Stacks are used
networks, railway networks, and flight routes.
for managing interrupts and context switching.-
Nodes represent locations, and edges represent
Robot motion planning: Stacks can be used to
the connections between them.
store movements for path planning.
3. **Computer Networks**: Graphs are employed
4. Queues: to model computer networks, with nodes
Queues follow the First-In-First-Out (FIFO) representing devices (computers, routers) and
principle, where the first element inserted is edges representing physical or logical
the first one to be removed. They are used for connections between them.
tasks that require sequential processing, like 4. **Recommendation Systems**: Websites like
process scheduling, printing jobs, and message Amazon and Netflix use graphs to recommend
handling. products or movies to users. Nodes represent
applications of Queues: users or items, and edges represent preferences
- Traffic management: Queues are utilized to or similarities between them.
manage incoming traffic at intersections. 5. **Circuit Design**: Electrical circuits can be
- Real-time data processing: Queues are represented using graphs, where nodes
employed to handle data streams in real-time represent components and edges represent
applications. connections.
(U1)Linear search algorithm
The linear search algorithm is a
simple search algorithm used to
Complexity of Linear Search Algorithm
Linear search executes in O(n) time where n is the number of elements in the
find a specific element within a array. Obviously,the best case of linear search is when VAL is equal to the first
list or array. It works by element of the array. In this case, only one comparison will be made. Likewise,
sequentially checking each the worst case will happen when either VAL is not present in the array or it is
element in the list, starting from equal to the last element of the array. In both the cases, n comparisons will
the first element and moving have to be made. However, the performance of the linear
search algorithm can be improved by using a sorted array.
through to the last one, until
the desired element is found or
until the entire list has been Example
searched. This method is
straightforward but not the most Suppose we have the following list of numbers:
efficient for large datasets, as it [22, 5, 8, 15, 3, 10, 7]
may require checking all And we want to search for the target element `10` in this list
elements in the worst case using the linear search algorithm.
scenario. Step-by-step explanation of the linear search algorithm:
Here's how the linear search 1)Start at the first element (index 0) of the list, which is `22`.
algorithm works: 2)Compare the target element (`10`) with the current element
1. Start at the first element of at the current index (`22`).
the list (index 0).
2. Compare the target element
3)The target element (`10`) does not match the current element
with the current element at the (`22`), so we move to the next element in the list.
given index. 4)Move to the second element (index 1) of the list, which is `5`.
3. If the target element matches 5)Compare the target element (`10`) with the current element
the current element, the search at the current index (`5`).
is successful, and the index is
returned.4. If the target element
6)The target element (`10`) does not match the current element
does not match the current (`5`), so we move to the next element in the list.
element, move to the next 7)Move to the third element (index 2) of the list, which is `8`.
element in the list and repeat 8)Compare the target element (`10`) with the current element
step 2. at the current index (`8`).
5. If the end of the list is
reached without finding the
9)The target element (`10`) does not match the current element
target element, the search is (`8`), so we move to the next element in the list.
unsuccessful, and the 10)Move to the fourth element (index 3) of the list, which is `15
algorithm returns a special value 11)Compare the target element (`10`) with the current element
(e.g., -1) to indicate that the at the current index (`15`).
element was not found.
12)The target element (`10`) does not match the current
Step 1: [INITIALIZE] SET POS=-1 element (`15`), so we move to the next element in the list.
Step 2: [INITIALIZE] SETI=1 13)Move to the fifth element (index 4) of the list, which is `3`.
Step 3: Repeat Step 4 while I<=N 14)Compare the target element (`10`) with the current element
Step 4: IF A[I] = VAL at the current index (`3`).
SET POS=I
PRINT POS 15)The target element (`10`) does not match the current
Go to Step 6 element (`3`), so we move to the next element in the list.
[END OF IF] 16)Move to the sixth element (index 5) of the list, which is `10`.
[END OF LOOP] 17)Compare the target element (`10`) with the current element
Step 6: EXIT at the current index (`10`).
SETI=I+1
Step 5: IF POS = –1 18)The target element (`10`) matches the current element (`10`
PRINT VALUE IS NOT PRESENT ), so we have found the target element!
IN THE ARRAY 19)Return the index `5`, which is the position of the target
[END OF IF] element `10` in the list.
(U1) Binary search algorithm (U1)TIME AND SPACE
COMPLEXITY:
Time Complexity:
Binary Search is an efficient algorithm for • The time complexity of an algorithm is the
finding a specific target value in a sorted amount of computing time required by an
algorithm to run its completion.
array. It repeatedly divides the search
• There are 2 types of computing time 1.
interval in half until the target value is found
Compile time 2. Run time
or the search interval is empty. • The time complexity generally computed at
Algorithm run time (or) execution time.
•The time complexity can be calculated in
1. Set left pointer to 0 and right pointer to terms of frequency count.
the length of the array - 1.
2. Repeat until the left pointer is less than • Frequency count is a count denoting the
or equal to the right pointer: number of times the statement should be
a. Calculate the middle index: mid = (left executed.
+ right) // 2 •The time complexity can be calculated as
b. If the target is equal to the value at Comments – 0
the middle index: Assignment / return statement – 1
Return mid (target found).
c. If the target is less than the value at Conditional (or) Selection Constructs – 1
the middle index: Space Complexity:
Update the right pointer to mid - 1 Space Complexity can be defined as amount
(discard the right half). of memory(or) space required by an Algorithm
d. If the target is greater than the value to run.
at the middle index:
Update the left pointer to mid + 1 To compute the space complexity we use 2
(discard the left half). factors i
3. If the loop completes without finding .Constant ii. Instance characteristics.
the target: • The space requirement S(p) can be given as
Return -1 (target not found). S(p) = C+Sp
Where C- Constant, it denotes the space
The complexity analysis taken for input and output.
1. Time Complexity: Sp – Amount of space taken by an instruction,
Binary Search has a time complexity of O variable and identifiers.
(log n), where "n" is the number of
elements in the sorted array. The reason
for this efficiency comes from the fact that
Binary Search continuously divides the
search space in half with each comparison.
As a result, the algorithm reduces the
search space to half at each step.
Therefore, the time complexity is
logarithmic.
2. Space Complexity:
The space complexity of Binary Search is O
(1) because it only requires a few constant
extra memory locations to store the
pointers or variables (e.g., left, right, mid)
used during the search process. The space
used does not increase with the size of the
input array, making it a space-efficient
algorithm.
(U1)Fibonacci search Algorithm
The Fibonacci Search algorithm is a
search technique that efficiently The complexity analysis
searches for an element in a sorted 1. Time Complexity:
array. It is based on the Fibonacci The time complexity of generating the Fibonacci
sequence and uses golden ratio series depends on the method used to compute
properties to divide the search space in a the numbers. There are two common approaches:
way that reduces the number of a. Recursive Approach:
comparisons. The simplest way to generate Fibonacci
numbers is using a recursive function. However,
Fibonacci Search algorithm this method is highly inefficient as it involves
1. The array is sorted in ascending order. redundant calculations, resulting in exponential
2. Determine the Fibonacci numbers that time complexity. Specifically, the time complexity
are less than or equal to the length of of the recursive Fibonacci series is O(2^n), where
the array. These "n" is the position of the Fibonacci number to be
numbers will be used as indices for computed. Each recursive call leads to two more
recursive calls until it reaches the base cases.
comparison.
b. Dynamic Programming (Memoization
3. Initialize two pointers `left` and `right`
or Tabulation):
to the To optimize the recursive approach, dynamic
first and second Fibonacci numbers, programming techniques like memoization or
respectively, and set the variable `mid` to tabulation can be used. Memoization stores the
0. computed Fibonacci numbers in a cache to avoid
4. While the target value is not found redundant calculations, while tabulation builds the
and `left` is less than or equal to `right`, series iteratively. With these approaches, the
time complexity is reduced to O(n) since each
do the following: Fibonacci number is computed only once.
a. Calculate the index `mid` using the
2. Space Complexity:
formula: `mid = left + fibonacci(right -
a. Recursive Approach:
left - 1)`. The space complexity of the recursive
b. If the value at index `mid` is equal approach is O(n) due to the recursive call stack.
to the The maximum depth of the call stack is "n" when
target, return `mid` (target found). computing the "n"-th Fibonacci number.
c. If the value at index `mid` is less b. Dynamic Programming (Memoization
than the or Tabulation):
target, update `left` to `mid + 1` to The space complexity for the dynamic
search in the right subarray. programming approach is O(n) as well.
Memoization uses a cache to store the
d. If the value at index `mid` is greater intermediate Fibonacci values, and tabulation
than requires an array of size "n" to store all the
the target, update `right` to `mid - 1` to Fibonacci numbers up to the "n"-th position.
search
in the left subarray.
e. Continue the loop until the target is
found or the subarray becomes empty.
(U5) BFS ALGORITHM (U5)Kruskal's algorithm for
generating a minimum
The Breadth-First Search (BFS) algorithm is a graph spanning tree
traversal algorithm that explores all the vertices of a
graph level by level. It starts from a chosen source Kruskal's algorithm is a greedy algorithm
vertex and visits all its neighbors before moving on to used to find the minimum spanning tree
their neighbors. BFS is typically implemented using a (MST) of a connected, undirected graph. A
queue data structure to keep track of the vertices to minimum spanning tree is a subset of the
be visited. edges that connects all the vertices of the
Applications of BFS algorithm: graph with the minimum possible total
1. Shortest Path and Minimum Spanning Tree: BFS can edge weight, without forming any cycles.
be used to find the shortest path between two Here's a step-by-step explanation of
vertices in an unweighted graph or to find the Kruskal's algorithm:
minimum spanning tree of a graph. 1. **Sort Edges by Weight:** First, sort all
2. Connected Components: BFS can help find the edges of the graph in non-decreasing
connected components in an undirected graph. order of their weights. This can be done
3. Web Crawling: BFS is used in web crawling to efficiently using various sorting algorithms,
discover and index web pages. such as quicksort or mergesort.
4. Social Networking: BFS can be used to find 2. **Initialize the MST:** Create an empty
connections and relationships between users in a set to represent the MST.
social network. 3. **Iterate over Edges:** Start iterating
5. Puzzle Solving: BFS can be applied to solve various over the sorted edges in ascending order
puzzles like sliding puzzles or mazes. of their weights.
6. Network Broadcast: BFS is used in network 4. **Check for Cycle:** For each edge,
protocols to broadcast information efficiently. check if adding it to the MST would create
a cycle. A cycle is formed if the two
BFS Algorithm: vertices of the edge already belong to the
1. Start with a source vertex and enqueue it into a same connected component in the MST. To
queue. check for cycles efficiently, you can use
2. Mark the source vertex as visited to avoid the disjoint-set data structure (also known
processing it again. as a union-find data structure).
3. While the queue is not empty: 5. **Add Edge to MST:** If adding the edge
a. Dequeue a vertex from the front of the queue. does not create a cycle (i.e., the two
b. Process the dequeued vertex (print it or do some vertices are not already connected), add
other operation). the edge to the MST. Also, merge the two
c. Enqueue all unvisited neighbors of the dequeued connected components in the disjoint-set
vertex into the queue and mark them as visited. data structure.
BFS Example: 6. **Repeat:** Continue this process until
Let's consider an undirected graph: the MST contains V-1 edges, where V is the
A -- B number of vertices in the original graph.
/\ | An MST for a connected graph with V
C D--E vertices will always have V-1 edges.
Starting from vertex A, we apply BFS: 7. **Output:** The final MST obtained after
1. Start with A: Queue = [A], Visited = {A} the iterations will be the minimum spanning
2. Dequeue A, visit it, and enqueue its neighbors: tree of the original graph.
Queue = [B, C, D], Visited = {A, B, C, D} The key idea behind Kruskal's algorithm is
3. Dequeue B, visit it, and enqueue its neighbors: to repeatedly add the minimum-weight
Queue = [C, D, E], Visited = {A, B, C, D, E} edge to the MST as long as it does not
4. Dequeue C, visit it, and enqueue its neighbors (none create a cycle. By adding edges in
in this case): Queue = [D, E], Visited = {A, B, C, D, E} increasing order of weights and avoiding
5. Dequeue D, visit it, and enqueue its neighbors (none cycles, the algorithm guarantees that the
in this case): Queue = [E], Visited = {A, B, C, D, E} final tree will be a minimum spanning tree.
6. Dequeue E, visit it, and enqueue its neighbors (none Kruskal's algorithm has a time complexity
in this case): Queue = [], Visited = {A, B, C, D, E} of O(E log E), where E is the number of
The BFS traversal order would be: A, B, C, D, E. edges in the graph.
(U5) Representation of graphs
In computer science and mathematics, a graph is a data structure that consists of a
finite set of vertices (or nodes) connected by edges (or links). It is a way to
represent relationships between different objects or entities. Graphs are used in a
wide range of applications, including computer networks, social networks,
transportation systems, and more.
There are several ways to represent a graph data structure, each with its own
advantages and use cases. The most common representations are:
1. Adjacency Matrix:
An adjacency matrix is a two-dimensional array where the rows and columns
represent vertices in the graph. The entry in the matrix at position (i, j) is 1 if there
is an edge between vertex i and vertex j, and 0 if there is no edge. For an undirected
graph (where edges have no direction), the matrix is symmetric across the main
diagonal.
Advantages:
- Efficient for dense graphs (where the number of edges is close to the maximum
possible).
- Easy to check if there is an edge between two vertices in O(1) time.
Disadvantages:
- Inefficient for sparse graphs (where the number of edges is significantly lower
than the maximum possible).
- Consumes more memory for large graphs with many vertices.
2. Adjacency List:
An adjacency list is a collection of lists or arrays where each list represents a vertex
in the graph, and the elements of the list are the vertices that are directly
connected to the corresponding vertex.
Advantages:
- Efficient for sparse graphs as it only consumes memory proportional to the number
of edges.
- Allows easy iteration over neighbors of a vertex.
Disadvantages:
- Slower to check for the presence of an edge between two vertices (O(degree)
time complexity, where degree is the number of edges incident to a vertex).
3. Edge List:
An edge list is simply a list of all the edges in the graph. Each edge is represented by
a pair (u, v) denoting a connection between vertex u and vertex v.
Advantages:
- Simple and easy to implement.
- Compact representation for graphs with a large number of edges.
Disadvantages:
- Checking for the presence of an edge or finding neighbors of a vertex can be
inefficient, especially for large graphs.
4. Incidence Matrix:
An incidence matrix is a two-dimensional array where rows represent vertices and
columns represent edges. The entry in the matrix at position (i, j) is 1 if vertex i is
part of edge j, and 0 otherwise.
Advantages:
- Useful for certain algorithms in graph theory.
Disadvantages:
- More complex to work with compared to adjacency matrix and list representations.
- Inefficient for graphs with a large number of edges.
generating a
(U5)Dijkstra's shortest (U5) minimum spanning
tree using Prim’s
path and perform algorithm.
complexity analysis Generating a minimum spanning tree (MST)
using Prim's algorithm is a popular and
efficient method for finding the smallest
Dijkstra's algorithm is used to find the shortest path tree that spans all the vertices of a
from a source vertex to all other vertices in a connected, undirected graph. The procedure
weighted graph with non-negative edge weights. The can be summarized in the following steps:
algorithm maintains a set of vertices whose shortest 1. **Initialize**: Start with an arbitrary node
distance from the source vertex is known and as the starting point and mark it as visited
continuously expands this set until all vertices have . Create an empty MST to store the edges
been included. of the minimum spanning tree and a priority
Here's the pseudocode for Dijkstra's algorithm: queue (min-heap) to store the edges
function Dijkstra(Graph, source): sorted by their weights.
create empty set S 2. **Add neighboring edges**: Add all the
create a set Q containing all vertices edges connected to the initial node into the
set the distance to source to 0 priority queue. These edges represent the
while Q is not empty: potential candidates for expanding the MST.
3. **Iterate until MST is complete**: While the
u = vertex in Q with the minimum distance
priority queue is not empty, do the following:
add u to S a. Extract the minimum-weight edge from the
remove u from Q priority queue. This edge will be a candidate for
for each neighbor v of u: expanding the MST.
if v is in Q: b. Check if adding this edge to the MST will form
a cycle. If adding the edge will not create a cycle,
new_distance = distance[u] + weight(u, v)
add it to the MST and mark the corresponding node
if new_distance < distance[v]: as visited.
distance[v] = new_distance c. If adding the edge will create a cycle (i.e., both
return distance nodes of the edge are already visited), discard the
edge and continue to the next iteration.
the complexity of Dijkstra's algorithm: 4. **Termination**: The algorithm terminates when
1. **Initialization**: In this step, we set the distance of all vertices are visited or when the priority queue
all vertices to infinity (except the source) and add all becomes empty. At this point, the MST is complete,
vertices to the set Q. This takes O(V) time, where V is and you have the minimum spanning tree of the
original graph.
the number of vertices.
Here's a pseudo-code representation of the Prim's
2. **Main Loop**: The main loop runs V times because algorithm:
in each iteration, we find the vertex with the minimum prim(graph):
distance not yet processed and add it to the set S. start_node = any_node_in_graph
Each iteration involves finding the minimum distance visited = {start_node}
mst = []
vertex, which can be done in O(V) time. Therefore, the
priority_queue = priority_queue_with_edges_
main loop takes O(V^2) time. connected_to(start_node) while priority_queue is
3. **Inner Loop (relaxation)**: In each iteration of the not empty:
main loop, we relax the edges from the newly added edge = extract_min_from_priority_queue
vertex to its neighbors. For each vertex, we explore all (priority_queue)
if edge.node1 not in visited or edge.node2 not
its neighbors, and this operation takes O(E) time,
in visited:
where E is the number of edges in the graph. Since mst.append(edge)
this inner loop runs V times, the total time complexity if edge.node1 not in visited:
for relaxation is O(V*E). visited.add(edge.node1)
Overall, the time complexity of Dijkstra's algorithm is add_edges_connected_to(edge.node1,
priority_queue)
dominated by the main loop's complexity, making it O(V
if edge.node2 not in visited:
^2). However, with a min-priority queue (e.g., visited.add(edge.node2)
implemented using a binary heap or Fibonacci heap), add_edges_connected_to(edge.node2,
the time complexity can be improved to O(E + V*log(V)) priority_queue)
, which is more efficient for sparse graphs.
return mst

You might also like