Data Structures and Algorithm Module 1,2,3
Data Structures and Algorithm Module 1,2,3
Module-1
<-Or->
➔ Graphs:-A graph can be defined as group of vertices and edges that
are used to connect these vertices.
-A graph G can be defined as an ordered set G(V, E) where V(G)
represents the set of vertices and E(G) represents the set of edges
which are used to connect these vertices.
-Ex: A Graph G(V, E) with 5 vertices (A, B, C, D, E) and six edges ((A,B),
(B,C), (C,E), (E,D), (D,B), (D,A)) is shown in the following figure.
*Data Structure operations:-This are the 4 common operations that can be performed
on the data structures are:
● Traversing:- Traversing a Data Structure means to visit the element stored in it.
-For example, traversing is required while printing the names of all the employees in
a department.
● Searching:- Searching means to find a particular element in the given data-structure.
-It is considered as successful when the required element is found.
- For example, we can use the search operation to find the names of all the
employees who have the experience of more than 5 years.
-We can search for any element in a data structure.
● Insertion:- We can also insert the new element in a data structure.
-For example, we can use the insertion operation to add the details of a new
employee the company has recently hired.
● Deletion:- We can also perform the delete operation to remove the element from
the data structure.
-For example, we can use the deleting operation to delete the name of an employee
who has left the job.
-The Following two operations ,which are used in specific situations,they are;
● Sorting:- We can sort the elements of a data structure either in an ascending or
descending order.
-For example, we can use the sorting operation to arrange the names of employees
in a department in alphabetical order
● Merging:-Combining the records in two different sorted files into a single sorted file.
#Algorithms:-An algorithm is a well defined list of steps for solving a particular problem.
-The time and space it uses are the two major measures of the efficiency of an algorithm.
-The formal definition of an algorithm is that it contains the finite set of instructions which
are being carried in a specific order to perform the specific task.
-It is not the complete program or code; it is just a solution (logic) of a problem.
-Ex: Algorithm to add two numbers and display the result.
Step 1 − START
Step 2 − declare three integers a, b & c
Step 3 − define values of a & b
Step 4 − add values of a & b
Step 5 − store output of step 4 to c
Step 6 − print c
Step 7 − STOP
->Advantages of Algorithms:
-It is easy to understand.
-An algorithm is a step-wise representation of a solution to a given problem.
-In Algorithm the problem is broken down into smaller pieces or steps hence, it is easier for
the programmer to convert it into an actual program.
-It helps in programming.
-It helps in debugging.
->Disadvantages of Algorithms:
-Writing an algorithm takes a long time so it is time-consuming.
-Understanding complex logic through algorithms can be very difficult.
-Branching and Looping statements are difficult to show in Algorithms(imp).
-No standard form to write an algorithm text.
*Performance Measurement:- is used to find performance of any algorithm.
-The performance of the algorithm is mainly dependent on space and time complexity.
-The space complexity means how much space is needed for storing the given algorithm.
-The time complexity means how much time needed to compute the given algorithm.
-The space and time complexity mainly depends on the compile time and the runtime.
- The measurement of performance mainly depend on the runtime because if we take any
program the program must compile at once.
-bakki google
->Advantage of array
● Easier to declare and use
● Can be used with most of the data type
● Easy to find elements
● Multi dimensional
->Disadvantage of array
● Wastage of memory space if all array elements are not used.
● Size of an array is fixed once declared
● Array is homogenous. It means that the elements with similar data type can be
stored in it.
* Ordered lists:-One of the simplest and most commonly found data object is the
ordered or linear list.
-Eg: (monday,tue,wed,thu,fri,sat,sun)
-or the values in a card deck (2,3,4,5,6,7,8,9,10,jack,queen,king,Ace).
-This are the various operations that can be performed on the ordered lists they are;
● Find the length of the list
● Read the list from left to right or right to left.
● Recover the i-th element
● Store a new value into the i-th position
● Delete the element from the i-th position.
-The most common way to represent an ordered list is by an array.
→Algorithm :
1. If both the numbers are null then return
2. else if compare the power, if same then add the coefficients and recursively call
addPolynomials on the next elements of both the numbers.
3. else if the power of first number is greater then print the current element of first
number and recursively call addPolynomial on the next element of the first
number and current element of the second number.
4. else print the current element of the second number and recursively call
addPolynomial on the current element of first number and next element of
second number.
*Stack:- Stack is a linear data structure that follows the LIFO (Last-In-First-Out) principle.
-Stack has one end, whereas the Queue has two ends (front and rear).
-It contains only one pointer top pointer pointing to the topmost element of the stack.
-Whenever an element is added in the stack, it is added on the top of the stack, and the
element can be deleted only from the top of stack.
-In other words, a stack can be defined as a container in which insertion and deletion can be
done from the one end known as the top of the stack.
→Working of Stack:-Stack works on the LIFO pattern.
-As we can observe in the below figure there are five memory blocks in the stack; therefore,
the size of the stack is 5.
-Suppose we want to store the elements in a stack and let's assume that stack is empty.
-We have taken the stack of size 5 as shown below in which we are pushing the elements
one by one until the stack becomes full.
-Algorithm of Push
PUSH(STACK, TOP, MAXSTACK, ITEM)
This procedure pushes an ITEM onto a stack.
👇
*Application of stacks
👇
● Evaluation of Arithmetic Expressions:- explanation
● Expression Conversion:-explanation
● Backtracking:- explain cheyandaa
● Memory Management:- explain cheyandaa
► Infix to Postfix:-To convert infix expression to postfix expression, first Scan the infix
expression from left to right.
-Whenever we get an operand, add it to the postfix expression and if we get an operator or
parenthesis add it to the stack by maintaining their precedence.
▪️ Algorithm
Step 1: Consider the next element in the input.
Step 2: If it is operand, display it.
Step 3: If it is opening parenthesis, insert it on stack.
Step 4: If it is an operator, then
If stack is empty, insert operator on stack.
If the top of stack is opening parenthesis, insert the operator on stack
If it has higher priority than the top of stack, insert the operator on stack.
Else, delete the operator from the stack and display it, repeat Step 4.
Step 5: If it is a closing parenthesis, delete the operator from stack and display them
until an opening parenthesis is encountered. Delete and discard the opening
parenthesis.
Step 6: If there is more input, go to Step 1.
Step 7: If there is no more input, delete the remaining operators to output.
–>evaluation of postfix expressions:-Scan the expression from left to right and keep on
storing the operands into a stack.
-Once an operator is received, pop the two topmost elements and evaluate them and push
the result in the stack again.
-Consider the expression: Ex : 2 3 1 * + 9 -
● Scan 2, it’s a number, So push it into the stack. Stack contains ‘2’.
● Scan 3, again a number, push it to stack, stack now contains ‘2 3’ (from bottom to
top)
● Scan *, it’s an operator. Pop two operands from stack, apply the * operator on
operands.
-We get 3*1 which results in 3. We push the result 3 to stack.
-The stack now becomes ‘2 3’.
● Scan +, it’s an operator. Pop two operands from stack, apply the + operator on
operands.
-We get 3 + 2 which results in 5. We push the result 5 to stack.
-The stack now becomes ‘5’.
● There are no more elements to scan, we return the top element from the stack
(which is the only element left in a stack).
-So the result becomes -4.
►Algorithm
Step 1:Read the expression from left to right.
Step 2:If the element encountered is an operand, push it into the stack.
Step 3:If the element encountered is an operator, pop two operands a and b from the
stack, apply the operator (b operator a) and push the result back into the stack.
Or
Step 1:Scan the given expression from left to right and do the following for every
scanned element.
Step 2:If the element is a number, push it into the stack.
Step 3:If the element is an operator, pop operands for the operator from the stack.
Evaluate the operator and push the result back to the stack.
Step 4:When the expression is ended, the number in the stack is the final answer.
-Example :2 4 3 + * 5 - )
->Advantages of Stack:-
● Easy implementation
● A Stack helps to manage the data in the ‘Last in First out’ method.
● It allows you to control and handle memory allocation and deallocation.
● Insertion and deletion from one place.
->Disadvantages of Stack:-
● It is difficult in Stack to create many objects as it increases the risk of the Stack
overflow.
● It has very limited memory.
● In Stack, random access is not possible.
● Stack overflow and underflow
*Queue:-A queue to be a list in which all additions to the list are made at one end, and all
deletions from the list are made at the other end.
Or
-A queue can be defined as an ordered list which enables insert operations to be performed
at one end called REAR and delete operations to be performed at another end called FRONT.
→Types of Queue:-There are four different types of queue that are listed as follows
1. Simple Queue or Linear Queue:-In Linear Queue, an insertion takes place from one
end while the deletion occurs from another end.
-The end at which the insertion takes place is known as the rear end, and the end at
which the deletion takes place is known as front end.
-It strictly follows the FIFO rule.
-The major drawback of using a linear Queue is that insertion is done only from the
rear end.
-If the first three elements are deleted from the Queue, we cannot insert more
elements even though the space is available in a Linear Queue.
- In this case, the linear Queue shows the overflow condition as the rear is pointing
to the last element of the Queue.
2. Circular Queue:-It is similar to the linear Queue except that the last element of the
queue is connected to the first element.
- It is also known as Ring Buffer, as all the ends are connected to another end.
- The representation of circular queue is shown in the below image
-The drawback that occurs in a linear queue is overcome by using the circular queue.
-If the empty space is available in a circular queue, the new element can be added in
an empty space by simply incrementing the value of rear.
-The main advantage of using the circular queue is better memory utilization.
-Example:
Front= -1
Rear= -1
-Add 10
Front= 0
Rear= 0
-Add 20 and 30
-Add 40 and 50
-dequeue 10 and 20
-Add 60
-Add 70
3. Priority Queue:-It is a special type of queue in which the elements are arranged
based on the priority.
-It is a special type of queue data structure in which every element has a priority
associated with it.
-Suppose some elements occur with the same priority, they will be arranged
according to the FIFO principle.
-The representation of priority queue is shown in the below image
-Insertion in priority queue takes place based on the arrival, while deletion in the
priority queue occurs based on the priority.
-There are two types of priority queue that are discussed as follows -
● Ascending priority queue - In ascending priority queue, elements can be
inserted in arbitrary order, but only smallest can be deleted first.
-Suppose an array with elements 7, 5, and 3 in the same order,
-so, insertion can be done with the same sequence, but the order of deleting
the elements is 3, 5, 7.
● Descending priority queue - In descending priority queue, elements can be
inserted in arbitrary order, but only the largest element can be deleted first.
-Suppose an array with elements 7, 3, and 5 in the same order,
-so, insertion can be done with the same sequence, but the order of deleting
the elements is 7, 5, 3.
4. Deque/Double Ended Queue :-In Deque or Double Ended Queue, insertion and
deletion can be done from both ends of the queue either from the front or rear.
-It means that we can insert and delete elements from both front and rear ends of
the queue.
-The representation of the deque is shown in the below image
-There are the following operations that can be applied on a deque
● Insertion at front
● Insertion at rear
● Deletion at front
● Deletion at rear
-There are two types of deque that are discussed as follows -
● Input restricted deque - As the name implies, in input restricted queue,
insertion operation can be performed at only one end, while deletion can be
performed from both ends.
Push and pop at the top of the stack Enqueue elements at the back of the queue
And dequeue elements from the front of
the queue
Stack does not have any types. Queue is of three types – 1. Circular Queue
2. Priority queue 3. double-ended queue.
#Linked List:-A linked list is a linear data structure, in which the elements are not stored
at contiguous memory locations.
-The elements in a linked list are linked using pointers.
-A linked list consists of nodes where each node contains a data field and a reference(link) to
the next node in the list.
-If start / head is null it means linked list is empty.
Start =4
INFO[4]=41 LINK[4]=2
INFO[2]=42 LINK[2]=5
INFO[5]=43 LINK[5]=1
INFO[1]=44 LINK[1]=3
INFO[3]=45 LINK[3]=6
INFO[6]=46 LINK[6]=0 /end of the linked list
-There are three types of linked lists They are;
1. Singly Linked List − The nodes only point to the address of the next node in the list.
➢ Insertion at beginning
● Searching:-In searching, we match each element of the list with the given
element. If the element is found on any of the location then location of that
element is returned otherwise null is returned.
-Searching can be performed in sorted list and unsorted list.
➢ List is unsorted
➢ LIst is sorted
2. Doubly Linked List − The nodes point to the addresses of both previous and next
nodes.
-Doubly Linked Lists contain three “buckets” one bucket holds the data and the
other two buckets hold the addresses of the previous and next nodes in the list.
-In a singly linked list, we could traverse only in one direction, because each node
contains address of the next node and it doesn't have any record of its previous
nodes.
-However, doubly linked list overcome this limitation of singly linked list.
-Due to the fact that, each node of the list contains the address of its previous node,
we can find all the details about the previous node as well by using the previous
address stored inside the previous part of each node.
→Operations on doubly linked list:- There are various operations which can be
performed on doubly linked list they are; Insertion ,Deletion ,Traverse and Searching.
● Insertion:- The insertion into a doubly linked list can be performed at
different positions.
-Based on the position of the new node being inserted, the insertion is
categorized into the following categories they are;
-Allocate the memory for the new node. Make the pointer ptr point to the new node
being inserted.
-Check whether the list is empty or not. The list is empty if the condition head == NULL
holds. In that case, the node will be inserted as the only node of the list and therefore the
prev and the next pointer of the node will point to NULL and the head pointer will point to
this node.
-In the second scenario, the condition head == NULL become false. The new node will be
inserted as the last node of the list. For this purpose, we have to traverse the whole list in
order to reach the last node of the list. Initialize the pointer temp to head and traverse the
list by using this pointer.
-the pointer temp point to the last node at the end of this while loop. Now, we just need
to make a few pointer adjustments to insert the new node ptr to the list. First, make the
next pointer of temp point to the new node being inserted i.e. ptr.
-make the previous pointer of the node ptr point to the existing last node of the list i.e.
temp.
-make the next pointer of the node ptr point to the null as it will be the new last node of
the list.
➢ Insertion after specified node:-Adding the node into the linked list
after the specified node.
-Algorithm
Explanation
-Allocate the memory for the new node.
-Traverse the list by using the pointer temp to skip the required number of nodes in order
to reach the specified node.
-The temp would point to the specified node at the end of the for loop. The new node
needs to be inserted after this node therefore we need to make a fer pointer adjustments
here. Make the next pointer of ptr point to the next node of temp.
-make the prev of the new node ptr point to temp.
-make the next pointer of temp point to the new node ptr.
-make the previous pointer of the next node of temp point to the new node.
● Deletion :-we want to delete the node in the doubly linked list we have three
ways to delete the node in another position.
➢ Deletion at beginning
➢ Deletion at last
-In Disadvantages, Doubly linked list occupy more space and often more
operations are required for the similar tasks as compared to singly linked lists.
-It is easy to reverse the linked list.
● Traverse :-Visiting each node of the list at least once in order to perform some
specific operation like searching, sorting, display, etc.
-Algorithm
★ IF HEAD == NULL
WRITE "UNDERFLOW"
★ Copy the head pointer in any of the temporary pointer ptr.
★ then, traverse through the list by using while loop.
-Keep shifting value of pointer variable ptr until we find the last node.
-The last node contains null in its next part
★ Although, traversing means visiting each node of the list once to perform some
specific operation.
-Here, we are printing the data associated with each node of the list.
3. Circular Linked List − The last node in the list will point to the first node in the list. It
can either be singly linked or doubly linked.
-circular linked lists can exist in both singly linked list and doubly linked list.
-Since the last node and the first node of the circular linked list are connected, the
traversal in this linked list will go on forever until it is broken.
-Sparse Matrix Representations can be done in many ways following are two common
representations:
● Array representation/Triplet Representation:-In this representation, we consider
only non-zero values along with their row and column index values.
-In this representation, the 0th row stores the total number of rows, total number of
columns and the total number of non-zero values in the sparse matrix.
-For example, consider a matrix of size 5 X 6 containing 6 number of non-zero values.
-This matrix can be represented as shown in the image.
-Here the first row in the right side table is filled with values 5, 6 & 6 which indicates
that it is a sparse matrix with 5 rows, 6 columns & 6 non-zero values.
-The second row is filled with 0, 4, & 9 which indicates the non-zero value 9 is at the
0th-row 4th column in the Sparse matrix and so on.
● Linked list representation:- In this linked list, we use two different nodes namely
header node/index node and element node.
- Header node consists of three fields and element node consists of five fields as
shown in the image…
-This sparse matrix can be represented using linked representation as shown in the
below image.
-The very first node which is used to represent abstract information of the sparse matrix
(i.e., It is a matrix of 5 X 6 with 6 non-zero elements).
-In this representation, in each row and column, the last node right field points to its
respective header node.
#Trees:-A tree is also one of the data structures that represent hierarchical data.
-It is a collection of nodes that are connected by edges .
-The topmost node of the tree is called the root, and the nodes below it are called the child
nodes.
-Each node can have multiple child nodes, and these child nodes can also have their own
child nodes.
2. Complete Binary Tree:-The complete binary tree is a tree in which all the nodes are
completely filled except the last level.
3. Balanced Binary Tree:-The balanced binary tree is a tree in which both the left and
right trees differ by atmost 1.
-For example, AVL and Red-Black trees are balanced binary tree.
-The given tree is a balanced binary tree because the
difference between the left subtree and right subtree is zero.
*binary tree representation:-A binary tree data structure is represented using two
methods.
-These are the methods;
-To represent a binary tree of depth 'n' using array representation, we need one
dimensional array with a maximum size of 2n + 1.
2. Linked List Representation:-We use a double linked list to represent a binary tree. In
a double linked list, every node consists of three fields.
-First field for storing left child address, second for storing actual data and third for
storing right child address.
-In this linked list representation, a node has the following structure…
-The above example of the binary tree represented using Linked list representation is
shown as follows…
*algebraic expressions:-algebraic Expression trees are used to express a mathematical
expression in the form of a binary tree.
-Algebraic Expression trees are binary trees in which each internal (non-leaf) node is an
operator and each leaf node is an operand.
-For example, if we have an expression A * B + C / D.
*binary tree traversals:- Traversal is a process to visit all the nodes of a tree and may print
their values too.
-Because, all nodes are connected via edges (links) we always start from the root (head)
node. That is, we cannot randomly access a node in a tree.
-There are three ways which we use to traverse a tree
1. In - Order Traversal:-In this traversal method, the left subtree is visited first, then the
root and later the right sub-tree.
-We should always remember that every node may represent a subtree itself.
D→B→E→A→F→C→G
[L-N-R]
2. Pre - Order Traversal:-In this traversal method, the root node is visited first, then the
left subtree and finally the right subtree.
A→B→D→E→C→F→G
[N-L-R]
3. Post - Order Traversal:-In this traversal method, the root node is visited last, hence
the name.
-First we traverse the left subtree, then the right subtree and finally the root node.
D→E→B→F→G→C→A
[L-R-N]
-Example
● Preorder traversal: 27 14 10 19 35 31 42
● Inorder traversal: 10 14 19 27 31 35 42
● Post order traversal: 10 19 14 31 42 35 27
→Algorithm of pre-order:-
-Explanation note ill unde or text page:282
→Algorithm of in-order:-
*Balanced Trees:-A balanced binary tree is also known as height balanced tree.
-It is defined as binary tree in when the difference between the height of the left subtree
and right subtree is equal to 1.
The height of a tree is the number of edges on the longest path between the root node and
the leaf node.
-A balanced binary tree is a binary tree that follows the 3 conditions:
● The height of the left and right tree for any node does not differ by more than 1.
● The left subtree of that node is also balanced.
● The right subtree of that node is also balanced.
-Example:
-It is a type of binary tree in which the difference between the height of the left and the
right subtree for each node is either 0 or 1.
- In the figure above, the root node having a value 0 is unbalanced with a depth of 2 units.
→Application of Balanced Binary Tree:
1. AVL Trees:-AVL tree is a self-balancing Binary Search Tree (BST) where the difference
between heights of left and right subtrees cannot be more than one (0,-1,1) for all
nodes.
-The difference between the heights of the left subtree and the right subtree for any
node is known as the balance factor of the node.
-Tree is said to be balanced if balance factor of each node is in between -1 to 1,
otherwise, the tree will be unbalanced and need to be balanced.
-The above tree is AVL because the differences
between the heights of left and right subtrees
for every node are less than or equal to 1.
Balance Factor= h(TL) - h(TR)
● If balance factor of any node is 1, it means that the left sub-tree is one level higher
than the right sub-tree.
● If balance factor of any node is 0, it means that the left sub-tree and right sub-tree
contain equal height.
● If balance factor of any node is -1, it means that the left sub-tree is one level lower
than the right sub-tree.
→AVL Rotations:-After the insertion of element the balance factor of any node in
the AVL tree can lead to an unbalanced stage.
-To restore the balance of the BST we use some technique is called rotation.
- There are basically four types of rotations which are as follows:
►L L rotation
-The new element X is inserted in the left subtree of left subtree of A,
-the closest ancestor node whose BF(A) becomes +2 after insertion.
-To rebalance the search tree, it is rotated so as to allow B to be the root with BL and A to be
its left subtree and right child, and BR and AR to be the left and right subtrees of A.
-Eg: given figure is a BST and AVL tree
-All AVL tree are BST
-insert 36.
-After insertion it became a non AVL tree
Because of 2.
-To balance we have to
apply LL rotation.
-Because we add 36 at the LL side.
►R R rotation
-Fig 1 is a balanced
-The inserted node 65 cause it a unbalanced (fig:2)
-so we apply RR rotation
-because we add 55 at the right right subtree.
Eg:
-Fig a is balanced
-After insertion it become unbalanced.
-We apply LR rotation because we add 37 at the LR side.
-And we se 39 as root.
→types of graph
● Directed Graph :-In a directed graph, Edges represent a specific path from some
vertex A to another vertex B.
-Node A is called initial node while node B is called terminal node.
-A directed graph is shown in the following figure.
● Mixed Graph:-A graph with both undirected and directed edges is said to be mixed
graph.
● Null Graph: A null graph is defined as a graph which consists only the isolated
vertices.
-Example: The graph shown in fig is a null graph, and the vertices are isolated
vertices.
→Graph Terminology:-
1. Path:-A path can be defined as the sequence of nodes that are followed in order to
reach some terminal node V from the initial node U.
2. Closed Path:-A path will be called as closed path if the initial node is same as
terminal node.
-A path will be closed path if V0=VN.
3. Simple Graph:-A graph is said to be simple if there are no parallel and self-loop
edges.
4. Parallel edges or Multiple edges:-If there are two undirected edges with same end
vertices and two directed edges with same origin and destination, such edges are
called parallel edges or multiple edges.
5. Self-loop:-Edge (undirected or directed) is a self-loop if its two endpoints coincide
with each other.
6. Complete Graph:-A complete graph is the one in which every node is connected with
all other nodes.
-A complete graph contain n(n-1)/2 edges where n is the number of nodes in the
graph.
7. Weighted Graph:-In a weighted graph, each edge is assigned with some data such as
length or weight.
8. Adjacent Nodes:-If two nodes u and v are connected via an edge e, then the nodes u
and v are called as neighbours or adjacent nodes.
9. Degree of the Node:-A degree of a node is the number of edges that are connected
with that node. A node with degree 0 is called as isolated node.
10. Isolated vertex: It is the vertex that is not connected to any other vertices in the
graph.
→Representations of Graphs/sequential Representations of Graphs:-y Graph
representation, we simply mean the technique to be used to store some graph into the
computer's memory.
-A graph is a data structure that consist a sets of vertices (called nodes) and edges.
-There are two ways to store Graphs into the computer's memory:
1. Sequential representation:-In sequential representation, an adjacency matrix or
path matrix is used to store the graph.
A. Adjacency matrix:-In this representation, the graph is represented using a
matrix of size total number of vertices by a total number of vertices.
-That means a graph with 4 vertices is represented using a matrix of size 4X4.
In this matrix, both rows and columns represent vertices.
-This matrix is filled with either 1 or 0.
-Here, 1 represents that there is an edge from row vertex to column vertex
and 0 represents that there is no edge from row vertex to column vertex.
-For example:
-Eg:
-here x can reach x by travelling through x→w→z→x.
-And we mark 1 at the matrix.
-Travelling is according to direction.
Destination Link
→Adjacency list:-Consider the graph and the table shows the adjacency of
the node.
-Example 2:
*Graph Traversals:-Graph traversal is a technique used to search for a vertex in a graph.
-The graph has two types of traversal they are;.
1. Breadth First Search (BFS):-The Breadth First Search (BFS) traversal is an algorithm,
which is used to visit all of the nodes of a given graph.
-In this traversal algorithm one node is selected and then all of the adjacent nodes
are visited one by one.
-After completing all of the adjacent vertices, it moves further to check another
vertices and checks its adjacent vertices again.
→Algorithm of BFS
● Step 1:-
● Step 2:-visit its adjacent unvisited node.
● Step 3:-mark it as visited and display it.
● Step 4:-insert the visited node into the queue.
● Step 5:-if there are no adjacent node then remove first node from the queue.
● Step 6:-repeat the above step until the queue is empty.
And exit.
-Example:
-Here node A have no adjacent node unvisited so remove the node A from the
queue.
-because we visited all the adjacent node of A .
-And display node A in the output.
-Here node C have no more unvisited adjacent node therefore remove C from the
queue and add it to output.
-Next element in the queue is E and its adjacent node is already visited and there is
no more unvisited adjacent node remain.
-so remove node E from queue and add it to output.
-Next element is F,G and H and there is no more unvisited adjacent node remains to
this node.
-so remove it from queue and add it to output
-Process the children of node B and mark node D as visited and push it on the stack.
-Pop node from stack and process it because node D have no adjacent node.
-and we backtrack by popping it from stack.
___________________________________________________________________________
-The value of K, i.e., 41, is not matched with the first element of the array.
-So, move to the next element. And follow the same process until the respective
element is found.
-Now, the element to be searched is found. So algorithm will return the index of the
element matched.
→ Algorithm:
● Assume we need to find an element that is in an array in random order.
● Start with the first position and compare it to the target in order to search for
a target element.
● If the current element matches the target element, return the position of the
current element.
● If not, move on to the next one until we reach the very end of an array.
● If still unable to find the target, return-1
2. Binary Search:-The Binary search method is only suitable for searching in a sorted
array.
-In this method, the element that has to be searched is compared to the array's
middle element.
-Search is considered successful only if it matches the target.
-The binary search algorithm uses the divide-and-conquer approach, it does not
scan every element in the list, it only searches half of the list instead of going through
each element,
-Hence said to be the best searching algorithm because it is faster to execute as
compared to Linear search.
→Working:-searching an element 40 in the 13-element array, following figure shows
how binary search works:
11 22 30 33 40 44 55 60 66 77 80 88 99.
→Algorithm:
● Binary search:
➢ Space Complexity :-The space complexity of binary search is O(1).
➢ Time Complexity:
*Best Case Complexity - In Binary search, best case occurs when the
element to search is found in first comparison, i.e., when the first
middle element itself is the element to be searched. The best-case
time complexity of Binary search is O(1).
*Average Case Complexity - The average case time complexity of
Binary search is O(logn).
*Worst Case Complexity - In Binary search, the worst case occurs,
when we have to keep reducing the search space till it has only one
element. The worst-case time complexity of Binary search is O(logn).
#Sorting:-Sorting is the process of arranging the elements of an array so that they can be
placed either in ascending or descending order.
-For example, consider an array A = {A1, A2, A3, A4, ?? An }, the array is called to be in
ascending order if element of A are arranged like A1 > A2 > A3 > A4 > A5 > ? > An .
Eg:int A[10] = { 5, 4, 10, 2, 30, 45, 34, 14, 18, 9 )
-The Array sorted in ascending order will be given as;
A[] = { 2, 4, 5, 9, 10, 14, 18, 30, 34, 45 }
-There are many techniques by using which, sorting can be performed they are;
1. Insertion Sort:-insertion sort is a simple sorting technique.
-Insertion sort works similar to the sorting of playing cards in hands.
-It is assumed that the first card is already sorted in the card game, and then we
select an unsorted card.
-If the selected unsorted card is greater than the first card, it will be placed at the
right side; otherwise, it will be placed at the left side.
-Similarly, all unsorted cards are taken and put in their exact place.
-The same approach is applied in insertion sort.
-In selection sort, the first smallest element is selected from the unsorted array and
placed at the first position.
-After that second smallest element is selected and placed in the second position.
The process continues until the array is entirely sorted.
3. Heap sort:-A heap is a complete binary tree, and the binary tree is a tree in which
the node can have the utmost two children.
-A complete binary tree is a binary tree in which all the levels except the last level,
i.e., leaf node, should be completely filled.
-It works by creating a max or min heap from an unsorted array.
→Max heap:-The value of the root (N) >= The value of each of the children of N.
→Min heap:-The value at N<= the value at any of the children of N.
Eg: let’s take an unsorted array and try to sort it using heap sort.
Consider the array: arr[] = {4, 10, 3, 5, 1}.
-Build a complete binary tree from the array.
-heap insertion:-evidam
Ottu insertion inta example um same annu
-To transform into max heap: After that, the task is to construct a tree from that
unsorted array and try to convert it into max heap.
-To transform a heap into a max-heap, the parent node should always be greater
than or equal to the child nodes
-Here, in this example, as the parent node 4 is smaller than the child node 10, thus,
swap them to build a max-heap.
-Now, 4 as a parent is smaller than the child 5, thus swap both of these again and the
resulted heap and array should be like this:
→Perform heap sort: Remove the maximum element in each step and then
consider the remaining elements and transform it into a max heap.
-Delete the root element (10) from the max heap. In order to delete this node, try to
swap it with the last node, i.e. (1). After removing the root element, again convert it
into max heap.
-Resulted heap and array should look like this:
-Repeat the above steps and it will look like the following:
-Now remove the root (i.e. 3) again and perform heapify.
-Now when the root is removed once again it is sorted. and the sorted array will be
like arr[] = {1, 3, 4, 5, 10}.
-In the given array, the largest element is 736 that have 3 digits in it.
-So, the loop will run up to three times (i.e., to the hundreds place).
-That means three passes are required to sort the array.
● Pass 1:In the first pass, the list is sorted on the basis of the digits at 1's place.
● Pass 2:In this pass, the list is sorted on the basis of the next significant digits
(i.e., digits at 10th place).
-After the second pass, the array elements are -
● Pass 3:In this pass, the list is sorted on the basis of the next significant digits
(i.e., digits at 100th place).
-Now, the array is sorted in ascending order “doubt undakill note ill unde”
#Hashing:-Hashing is a technique or process of mapping keys, and values into the hash
table by using a hash function.
-It is done for faster access to elements.
-A Hash table is a data structure that stores some information, and the information has
basically two main components, i.e., key and value.
-The hash table can be implemented with the help of an associative array
-The efficiency of mapping depends on the efficiency of the hash function used.
-Hashing is a technique to convert a range of key values into a range of indexes of an array.
-We're going to use modulo operator to get a range of key values.
eg:Consider an example of hash table and the following items are to be stored.
Item are in the (key,value) format.
(1,20) , (2,70) , (42,80) , (4,25) , (12,44) , (14,32) , (17,11) , (13,78) , (37,98)
*Hash functions (9 marks):-The type of hash function are;
1. Division Method
2. Mid Square Method
3. Digit folding method
*Collision Resolution:-It is possible that two different key k1 and k2 will have the same
hash address.
-This situation is called collision.
-or when two values are stored at the same index, and this leads to the collision problem.
-To resolve these collisions, we have some techniques known as collision techniques.
-The following are the collision techniques:
➢ Step 3: Inserting 50
-Hash(25) = 50 % 7 = 1
-In our hash table slot 1 is already occupied. So, we will search for slot
1+12, i.e. 1+1 = 2,
-Again slot 2 is found occupied, so we
will search for cell 1+22, i.e.1+4 = 5,
-Now, cell 5 is not occupied so we will
place 50 in slot 5.
● Double Hashing technique:-It is the efficient method of collision resolution
technique.
-Because it uses double hash function to calculate the address of any key.
-This combination of hash functions is of the form
h(k, i) = (h1(k) + i * h2(k)) % n
-h1(k) and h2(k) are two different hash functions.
-i indicates a collision number, n indicates the hash table size.
-Eg:Insert the keys 27, 43, 692, 72 into the Hash Table of size 7. where first
hash-function is h1(k) = k mod 7 and
second hash-function is h2(k) = 1 + (k mod 5)
➢ Step 1: Insert 27
-27 % 7 = 6, location 6 is empty so insert 27 into 6 slot.
➢ Step 2: Insert 43
-43 % 7 = 1, location 1 is empty so insert
43 into 1 slot.
➢ Step 3: Insert 692
-692 % 7 = 6, but location 6 is already
being occupied and this is a collision
-So we need to resolve this collision using double hashing.
➢ Step 4: Insert 72
-72 % 7 = 2, but location 2 is already being occupied and this is a
collision.
-So we need to resolve this collision using double hashing.