DS Notes Unit-I To 3
DS Notes Unit-I To 3
UNIT I
Matrix
Matrix contain m rows and n columns.
Example
-27 3 4
6 8 7
2 1 3
-27 6 2
3 8 1
4 7 3
Sparse Matrix
Matrix contain many zero entries then the matrix is called sparse matrix.
Example:1
0 0 2
0 3 0
0 0 0
The above matrix consist of 3 rows and 3 columns (m=3, n=3).It contain totally 9
elements. From this only two elements are non-zero elements and 7 elements are zero
elements. So the above example is called sparse matrix.
Example:2
15 0 0 22 0 -15
0 11 3 0 0 0
0 0 0 -6 0 0
0 0 0 0 0 0
91 0 0 0 0 0
0 0 28 0 0 0
The above matrix contain 6 rows and 6 columns(m=6,n=6),it contain totally 36
elements.From this only 8 entries are non-zero elements and 28 elements are zero
elements. This matrix contains more zero entries than non-zero entries. So it is called
sparse matrix.
A 1 2 3
0 6 6 8
1 1 1 15
2 4 1 22
3 6 1 -15
4 2 2 11
5 3 2 3
6 4 3 -6
7 1 5 91
8 3 6 28
In this transpose matrix values are not stored consecutively. We need to insert the
elements in correct order.
Step 2:
Insert the elements in correct order.
A 1 2 3
0 6 6 8
1 1 1 15
2 1 5 91
3 2 2 11
4 3 2 3
5 3 6 28
6 4 1 22
7 4 3 -6
8 6 1 -15
Method:II
The method-I need two steps for find the transpose of sparse matrix. To avoid this we
use another effective transpose algorithm in method-II.
Algorithm
Algorithm Transpose (A,B)
// A is a sparse Matrix
// B is a Transpose Matrix
(m,n,t)(A(0,1),A(0,2),,A(0,3))
B(0,1),B(0,2),B(0,3)(n,m,t)
If (t<=0) then return
Q1
For col1 to n do
For p1 to t do
If A(p,2)=col then
[B(q,1),B(q,2).B(q,3)A(p,2),A(p,1),A(p,3)]
End
End transpose
Analysis of Algorithm
The time complexity of the above algorithm is O(n,t).When t=nm then time complexity of algorithm
becomes O(n2m).
Representation of Arrays
Array
Array is a collection of elements of same data type stored under a single name .Array
elements are stored in continuous memory locations. The total number of elements in
an array can be calculated by the formula
n
π (ui-li+1)
I=1
Here
α =1000,u1=5
Address of 3rd element is find using the formula α +(i−1).
=1000+(3-1)
= 1000+2
Address of 3rd element is=1002
Address of the last element is find using the formula α +(u 1−1),
=1000+(5-1)=1004
In the above example address of last element is 1004.
Representation of two dimensional array
Two dimensional array is stored in the table format.
Syntax
A(1:u1,1:u2)
Where u1 is number of rows and u2 is number of columns.
Address of the two dimensional array is represented in the row major order.Address of the A(1,1) is α ,
Address of A(i,j) is α + ( i−1 ) u2+ ( j−1 )
Example
A[3][3]={{10,20,30},{40,50,60},{70,80,90}}
A 1 2 3
1 Addr:[1001] Addr:[1002] Addr:[1003]
10
20 30
2 Addr:[1004] Addr:[1005] Addr:[1006]
40 50 60
3 Addr:[1007] Addr:[1008] Addr:[1009]
70 80 90
Stack
Stack is an ordered list in which all insertion and deletions are made at one end called top of the
stack.
Stack Functions
1. Create(S)-It is an empty stack.
2. Add(i,S)-Insert the element I to the stack S.
3. Delete(S)-It removes the top element of stack S.
4. Top(S)-It returns the top element of stack S.
5. ISEMT(S)-It return true if S is empty else it returns false.
Last In First Out[LIFO]
Last element inserted into the stack is removed first. So that stack is called Last In
First Out[LIFO] list.
Stack Operations
There are two operations in stack.
1. Insertion or Push: Insertion operation of stack is called push.
2. Deletion or POP: Deletion of stack is called pop.
Insertion or Push
Example
Insert A,B,C,D and E into the stack.
Initially top=0 stack size=5
Insert A
A
Insert B
B
A
Top=1+1=2
Insert C
C
B
A
Top=2+1=3
Insert D
D
C
B
A
top=3+1=4
Insert E
E
D
C
B
A
Top=4+1=5
Insert F
Stack is Full.(Not Inserted)
Algorithm
Procedure Add(item,stack,n,top)
//item-Inserted element
//n-Stack Size
//top-top of the stack
If top>=n then
Call Stack_full
Toptop+1
Stack(top)item
End Add
Deletion or Pop
Example
Stack
E
D
C
B
A
Delete
D
C
B
A
Top=top-1=5-1=4
Delete
C
B
A
Top=4-1=3
Delete
B
A
Top=3-1=2
Delete
A
Top=2-1=1
Delete
Top=1-1=0
Delete
Stack is Empty
Algorithm
Procedure Delete(item,stack,top)
//item-Deleted item
//n-Stack size
//top-Top of the stack
If top<=0 then
Call Stack_Empty
Itemstack(top)
Toptop-1
End Delete
System Example
Proc main() Proc A1 Proc A2 Proc A3
-------------- ----------- ----------------- -----------
--------------- ----------- ------------------ --------------
Call A1 Call A2 Call A3
R: S: T:
End End End End
In the above example main() is first invoked, then from the main() subroutine A1 is
called. A1 call A2 and then A2 call A3.After execution of A3 that is closed first and
then A2,A1 atlast main() is closed.
Queue
Queue is an ordered list in which insertions takes place at one end called rear end and
all deletions take place at the other end called front end.
Example
A B C D E
Front Rear
First In First Out List(FIFO)
The first element inserted into the queue is removed first.So that queue is
called FIFO list.
Queue Functions
CreateQ(Q)-It creates Q as an empty Queue.
AddQ(i,Q)-It adds element I to the rear of the queue.
DeleteQ(Q)-It removes the front element from the queue.
FrontQ(Q)-It returns the front element of the queue.
ISEMT(Q)-It returns true if queue is empty otherwise it returns false.
Queue Operations
There are two operations in queue.
1. Insertion
2. Deletion
Insertion Algorithm
Procedure AddQ(item,Q,n,rear)
//item-Inserted element
//Q-Queue
//n-Queue Size
//rear-Position of rear end
If rear>=n then
Call Queue is full
Rearrear+1
Q(rear)item
If front=0 then
Front1
End AddQ
Deletion Algorithm
Procedure DeleteQ(item,Q,front,rear)
// item-Deleted element
// Q-Queue name
// front-Position of front
//rear-Position of rear
If (front=0) then
Call queue is empty
ItemQ(front)
If(front=rear)then
Frontrear0
Else
Frontfront+1
End deleteQ
Drawback
In normal queue some times, some queue memory spaces are unused, because we can’t add new element
instead of deleted element’s memory space.It is avoided by using circular queue concept.
Circular Queue
Queue is represented in the form of circular format is called circular queue. In this queue, queue
elements Q(1..n) is added in the form of circular.
Example
B C
Front=1 rear=4
A D
Insertion Algorithm
Algorithm CQinsertion(Q,f,r,n,item)
If r=n then
R1
Else
R=r+1
If f=r then
Write(‘Overflow’)
Return
Q(R)item
If f=0 then
F=1
Return
End CQInsertion
Deletion Algorithm
Procedure CQDelete(f,r,Q,n,y)
//f-front
//r=rear
//Q-Queue
//n-Queue size
//y-Deleted element
If f=0 then
Write (‘Underflow’)
return
yQ(F)
if f=r then
fr0
return(y)
if f=n then
f1
else
ff+1
return(y)
end CQDelete
Dequeue
In dequque insertion can perform any end and also deletion can perform in any end.
Evaluation of Expression
An expression contains the operands, operators and delimeters. Expression can be represented in 3
types of notations.
1. Prefix notation
2. Infix notation
3. Postfix notation
1. Prefix notation
Operator is placed before the operand is called prefix notation.
Example
A+b
Prefix notation :+ab
2. Infix notation
Operator is placed in between the operand is called infix notation.
Example
Infix notation :a+b
Postfix notation
In this notation operator is placed after the operand .
Example
Infix :a+b
Prefix:+ab
Postfix:ab+
Operator Precedence
The operator having the priority itself. The operator priority as follows
Operator Priority
**,unary +, unary - 6
*,/ 5
+,- 4
<.<=,>.>=,=,!= 3
AND 2
OR 1
Example
Evaluate X=A/B**C+D*E-A*C where A=4 ,B=C=2 And D=E=3
X=A/B**C+D*E-A*C
=4/2**2+3*3-4*2
=4/4 + 3*3-4*2 (** Has high priority)
=1+9-8(/,* has equal priority)
=10-8(+,- has equal priority)
=2
If operators have equal priority in the given expression then it is evaluated from the left to right manner or
right to left manner according to the rule.
Evaluation of Postfix Expression
Algorithm
Procedure Eval(E)
Top0 // initialize stack
Loop
X=next_token(E)
Case
:x=’∞’: return // Answer is top of the stack
:x is an operand:
Call Add(x,stack,n,top)
:else:
Remove the correct number of operands for operator x from the
stack ,perform the operation and store the result onto the stack.
End
Forever
End eval
Steps
1. Add ∞ at the end of equvation.
2. Read the terms one by one from the equvation
3. If it is operand add it to top of the stack otherwise if it is operator then remove
operand from stack and perform operation and store the result in stack.
4. If it is ∞ then display the result from stack.
Example
AB+
1. X=AB+∞
2. Read A it is operand then it is added to stack.
A
Algorithm
Procedure Postfix(E)
Stack(1)’∞’
Top1
Loop
Xnext_token(E)
Case
:x=’∞’: while top>1 do //empty the stack
Print(stack(top));
Toptop-1
End
Print(‘∞’)
Return
:x is an operand: print(x)
:x=’)’: while stack(top)!= ‘(‘ do
Print(stack(top));toptop-1
End
Toptop-1 // delete ‘)’
:else: while ISP(stack(top))>=ICP(x) do
Print(stack(top));toptop-1;
End
Call Add(x,stack,n,top)) //insert x is stack
End
Forever
End postfix
In the same way insertion and deletion operations are performed in Multiple Queue.
Questions
One Mark
1. Define algorithm
2. Define data structure
3. What is time and space complexity?
4. What is sparse matrix?
5. Time complexity of sparse matrix transpose algorithm is------
6. What is array?
7. Write the formula for find the address of particular element is one dimensional array.
8. Write the formula for find the address of particular element is two dimensional array.
9. Write the formula for find the address of particular element is multi dimensional array.
10. Define stack.
11. Stack is an ---------List.
12. Define Queue.
13. Queue is an --------------List.
14. What is circular queue.
15. Define dequeue.
16. Convert following expression into infix to postfix
A*(B+C)*D
5 Marks
1. Write short notes on analyzing algorithm.
2. Describe about array representation.
3. Explain about multiple stack and queues.
4. Explain circular queue with example.
5. Explain various notations of equation.
8 Marks
1. Discuss in detail about stack operations.
2. Discuss in detail about queue operations.
3. Explain in detail about sparse matrix.
4. Explain infix to postfix conversion with example.
Unit-II
Linked List
In array insertion and deletion in between the element is difficult.So we use the format of the concept linked
list.
Definition
Linked list is a ordered list.It is used to represent the data.In linked list data is represented using collection of
nodes , each node contain two parts that is
1. Data (or) Information part
2. Link part
1.Data (or) Information part
Data part contains the element of the data item.
2.Link part
Link part contain the address of the next item. The address of the last item is always null.
Ex:
A,B,C
Creation of Node
Procedure create(T)
Call getnode(I)
TI;
Data(I)’MAT’;
Link(T)I
Link(I)0
Data(I)’PAT’
End create
MAT PAT 0
T
The above algorithm create the two nodes using getnode() function.
The link part of the first node point to the next node. The link part of the second
node is zero or null.
The first node contain the date ‘MAT’ and second node contain the data ‘PAT’.
Insertion Algorithm
Procedure Insert(T,X)
Call getnode(I)
Data(I)’OAT’
If(T==0) then
TI
Link(I)0
Else
Link(I)Link(X)
Link(X)I
End insert
The above algorithm ‘T’ is a pointer to the linked list X is the node procedding to the new node ‘I’.
The above algorithm used to insert the element first,middle and last of the linked list.
It create the new node I and store the data as ‘OAT’.
If T=0 then it add the new node as first node.
Ex:
T
I
OAT 0
OAT
Link(X)I
OAT
Link(X)I
Result
X
Insert below node into last of linked list
OAT
I
Link(I)Link(X)
Result
The above algorithm is used to delete the node from the first,middle and last of the linked list.
Example
T
Remove the first node CAT
Y=0
X=CAT
TLink(T)
PAT MAT 0
T
Remove the middle node PAT.
Y=CAT
X=PAT
Link(Y)Link(X)
MAT 0
CAT PAT
Link(X)0
Result
PAT MAT 0
Result
CAT PAT 0
Linked Stack
Stack is represent using linked list is called linked stack.Here T(i) is the top of the linked stack.In this
also insertion and deletion performed in the top of the stack.
Example
Example
T(i)
x 40
T(i) 30
20
10 0
T(i)
20
10 0
The above example node 30 is deleted.
Linked Queue
The queue represent using linked list is called linked queue.
Example
F(i)
R(i)
Example
10 20 30 0
Result
30 40
10 20
F(i) R(i)
10 20 30 0
F(i) R(i)
Result
10 20 0
10 20 30 0
Polynomial Addition
Polynomial Additions
Step 1: If exponents of two terms are equal then the co-efficients are added and a new term is created for the
result.
Step 2: If exponent of current term in A is less than the exponent of current term in B then duplicate of the
term B is created and attached to C.
Step 3 : if exp(A)>exp(B) then duplicate of the A is created and attached to C.
Step 4: Atlast remaining terms in A and B are added according to the exponential order.
A=3x14 +2x8 +1
B=8x14 -3x10 +10x6
Example
A=3x14 +2x8 +1
3 14 2 8 1 0 0
Example
B=8x14 -3x10 +10x6
8 14 -3 10 10 6 0
A+B=11x14 -3x10 +2x8 +10x6 +1
11 14 -3 10 2 8 1 0 0
10 6
Y=
y1 y2 y3 0
Example
Z=
x1 x2 x3 0 y1 y2 y3 0
Inversion
Invert operation give the reverse of the linked list.
Algorithm
Procedure Invert(X)
PX;
Q0;
While(P<>0) do
RQ;
QP;
PLink(P);
Link(Q)R;
End
XQ;
End invert
Example
X=
x1 x2 x3 0
X’=
x3 x2
x1 0
Head 3 3 0 0 0 0
0 0
0 0
1 3
10
2 1
0 0
15
0 0 3 2
20
Doubly Linked List
Double linked list is used to traverse the list both in forward and backward direction.Each node in
double linked list has two link fields and one data field.
Syntax
Plink Data Nlink
In doubly linked list plink of the first node and the nlink of the last node always null.
Creation of Doubly Linked List
Algorithm
Algorithm Create DList()
Step 1: Declare the structure for the node.
Step 2: Set the size of the node and allocate space in memory for the required node size.
Step 3: [Read node information]
Newnodedata=value
Newnodeplink=null
Newnodenlink=null
Step 4: [To connect new node with the list]
Set head=newnode
Set lastnode=newnode
Step 5:[To add more nodes]
a) Repeat step 1,2,3 and then
b) Assign
lastnodenlink=newnode
newnodeplink=lastnode
c) Lastnode=newnode
Goto(a)
end createDlist;
Example
Null A1 A B Null
Newnode Last
Head
Algorithm
Algorithm DLinsertlast(Head:Node)
Step 1: Create new node by allocating memory.
Step 2: [Intialize the new node]
Newnodedata=value
NewnodePlink=Null
NewnodeNlink=Null
Step 3: [if the list is empty]
If (Head=Null) then
Set Head=newnode
Stop
Step 4: [ if list is not empty]
LastNlink=newnode
Newnodeplink=last
Set last=newnode
End DLinsertlast;
Example
Null A B C Null
Head
Last
D Newnode
After insertion
Null A B C D Null
Head
Last
Algorithm
Algorithm DLinsertintermediate(Head : Node)
Step 1: Creating new node by allocating memory.
Step 2: [Read data value]
Newnodedata=value
NewnodePlink=Null
NewnodeNlink=Null
Step 3:[if list is empty]
If(Head = Null)
Set Head=newnode
Stop
Step 4: [ if list is not empty]
a) Read condition which states the position to insert
b) Traverse the list and locate A after which the insertion to be made.
If ( node data = condition) then
A=node
B=ANlnk
ANlink=newnode
BPlink=newnode
NewnodePlink=A
NewnodeNlink=B
End DLinsertintermediate;
Example
Null X Y Z Null
Head
Last
Insert node Y1 in between X and Y.
Here X is node A and Y is node B.
After insertion
Null X Y1 Y Z Null
Head
A newnode B Last
Assign Head=FirstNlink
FirstNlink=Null
SecondPlink=Null
End deletefirstDL;
Example
Null X Y1 Y Z Null
Head
First Last
After Deletion
Null Y1 Y Z Null
Head Last
Algorithm
Algorithm DeletelastDL()
Step 1:
If ( Head=Null) then
Print(“List is empty”)
Stop
Step 2:
Delnode=Lastnode
Assign Last=DelnodePlink
DelnodePlink=Null
LastNlink=Null
DeletelastDL;
Example
Null X Y1 Y Z Null
Head
First Last
After Deletion
Null X Y1 Y Null
Head Last
Deleting the Intermediate node
Make the Nlink of node A point to node B and Plink of node B point to node A.
Algorithm
Algorithm deleteintermediateDL()
Step 1:
If ( Head=Null) then
Print(“List is empty”)
Stop
Step 2:
If(nodedata=deldata) then
Begin
A=DelnodePlink
B=DelnodeNlink
ANlink=B
BPlink=A
DelnodeNlink=Null
DelnodePlink=Null
End
Else
Node=nodenlink
End deleteintermediateDL;
Example
Null X Y1 Y Z Null
Head
Last
After Deletion
Result
Null X Y1 Z Null
Head Last
No disconnectivity.
Disadvantages
In multiprogramming computer several programming reside in the computer memory at the same
time.
When the execution of the program is completed the allocated memory is released.
Example
Available memory 100000 words.Available programs 5.Their memory requirements given below
P1 10000 Words
P2 15000 Words
P3 6000 Words
P4 8000 words
P5 20000 Words
The above example memory is allocated continuously from the available memory.
Buddy System
If block of size M is not available then a larger block is split into two sub blocks. Each sub block is
called buddies. This process is repeated until a block of size M is produced.
Best fit strategy
Finding the free block whose size is closed to n as possible but not < n is called best fit strategy.
Garbage Collection
Garbage collection is the process of collecting all unused nodes and returning them to available
space.This process is perform using two phase
(i) The first phase is known as the marking phase all nodes in use are marked.
(ii) The second phase all unused nodes are returned to the available list.
(i) Marking Phase
Marking phase mark all directly accessible nodes and also indirectly accessible nodes.
In this method we use two algorithms known as mark1 and mark2 algorithms.
Mark1 Algorithm
In mark1 method we use two bit fields
(i) Mark field
It is used to check whether the block is used or not. If the mark field is 0 then the block
is not allocated otherwise if one then the block is already allocated.
0 1
Mark-2 Algorithm
The mark-2 algorithm overcomes the drawback of mark1 algorithm.
Algorithm
Step 1: Initially all nodes are marked as 0.
Step 2: Set the pointers X,P and T
X: Starting node
P:End point
T: Previous to P
Step 3:Traverse the node in the path T-X.Visit the node one by one using Dlink. If mark(Q)=0 set
Mark(Q)=1.
Step 4: After visit all the nodes in Plink set T and P, visit all nodes in Rlink. If mark(Q)=0 set
Mark(Q)=1.
Storage Compaction
When request of storage is fixed size then it is enough to just link all unmarked nodes together into an
available space list.
When request of storage is variable size then compact storage is needed. In this all free spaces are
combined into continuous block is called compact storage.
Example
0 1 0 1 0 1 1 0
N1 N2 N3 N4 N5 N6 N7 N8
In this
0-Not allocated node
1-allocated node
Available list is
AV N1 N3 N5 N8
Storage Compaction
N2 N4 N6 N7 N1+N3+N5+N8
Five mark
1. Write short nots on linked stack
2. Describe about linked queue
3. Explain about garbage collection
4. Explain about storage compaction.
Eight mark
1. Discuss in detail about single linked list.
2. Explain in detail about doubly linked list operations.
3. Explain polynomial addition with suitable example.
4. Explain in detail about dynamic memory storage management.
Unit-III
Types of Data structure
Data structure can be classified into two types .
(i) Linear Data Structure
(ii) Non-Linear data structure
Example
The above diagram
Path(A-C) is ABC
11. Depth or Height
The length of any longest path of the tree is called depth of the tree.
Example
The above diagram
Depth(AD)=3
Depth(AH)=4
Depth(AF)=3
Depth(AI)=4
Depth(AJ)=4
The length of the tree is 4.
12. Forest
A forest is a set of disjoint trees.
If root node is removed then any node becomes forest.
Example
The root node A is removed means following forest is Created
1. Linear representation
In this representation an array can be used to store the nodes of a binary tree.
Example
A
C
B
E
D
Linear representation
A B C D E
Example
Lchild(A)=2(0)+1
=1
Lchild(A)=B
Example
Linked Representation
B C
Advantages
Insertion and deletion is very easy.
Disadvantages
More memory space is required to store pointers.
1. Preorder Traversal
Steps
Step 1: Visit the root node
Step 2: Traverse the left subtree.
Step 3: Traverse the right subtree.
Preorder:ABC
Algorithm
Procedure preorder(T)
If (T!=0) then
Print(Data(T))
Call preorder(Lchild(T))
Call preorder(Rchild(T))
End preorder
Example
Preorder is ABDEHICFGJK
2. Postorder Traversal
Steps
Step 1: Traverse the left subtree.
Step 2: Traverse the right subtree.
Step 3: Visit root node
Example
Postorder:BCA
Algorithm
Procedure postorder(T)
If (T!=0) then
Call postorder(Lchild(T))
Call postorder(Rchild(T))
Print(Data(T))
End postorder
Example
Postorder is DHIEBFJKGCA
Inorder Traversal
Steps
Step 1: Traverse the left subtree.
Step 2: Visit root node
Step 3: Traverse the right subtree.
Example
Inorder:BAC
Algorithm
Procedure Inorder(T)
If (T!=0) then
Call Inorder(Lchild(T))
Print(Data(T))
Call Inorder(Rchild(T))
End Inorder
Example
Inorder is DBHEIAFCJGK
Example
B C
B C
Memory Representation of Threaded Binary Tree
Threaded Binary tree is represented in node format .In this each node contain 5 parts.
Lbit Lchild Data Rchild Rbit
In this Lbit is one if threaded binary tree’s left child contain normal pointer otherwise if it is threaded
pointer then Lbit is 0.
In this Rbit is one if threaded binary tree’s Right child contain normal pointer otherwise if it is
threaded pointer then Rbit is 0.
Example
HEADNODE
1 A 1
B 0 0 C 0
More on Binary trees
We can also perform some more operations on binary trees.That are
1. Copy
2. Equal
3. Propositional calculus
1. Copy
In copy operation on binary tree copy the one binary tree to another.
Algorithm:
Procedure copy(T)
Q=0;
If T<> 0 then
R=copy(Lchild(T))
S=copy(Rchild(T))
Call getnode(Q)
Lchild(Q)=R
Rchild(Q)=S
Data(Q)=Data(T)
Return(Q)
End copy
In this algorithm copy the tree from T to Q.
Example
Propositional Calculus
• Binary tree also used to represent propositional calculus.
• Ex: (X1^X2)V(X1^X3)
Tree Format
2. All the binary trees are combined together through the sibling field of the root node.
Example
FOREST
• The number of distinct binary trees is equal to the number distinct permutations obtained from that
nodes.
Graph
• Graph is a non-linear data structure.
• The graph consist set of vertices V and set of edges.
• G={V,E}
• V={v1,v2,….vn}
• E={e1,e2,…en}
EXAMPLE
Terminologies of Graph
1. Adjacent Vertices
Vertex A is set to be adjacent to vertex B if there is an edge between A and B.
In the above example
adjacent(A)={B,C,D}
Adjacent(B)={A,C,E}
2. Path
A path from vertex is a sequence of vertices each adjacent to the next.
In the above example
Path A-F is A-D-F
3. Cycle
A cycle is a path in which first and last vertices are the same.
In the above example
A-C-B-A is cycle.
4. Connected Graph
A graph is called connected if there exist a path from any vertex to any other vertex.
Example
5. Unconnected Graph
If graph contain unconnected components then it is called unconnected graph.
Example
6.Directed Graph
Each edge in the graph have a direction then the graph is called directed graph.
7.Degree of Undirected Graph
The number of edges incident on a vertex V is called degree of that vertex.
• Example
10.Weighted Graph
• If every edge in the graph is assigned some weight or value then the graph is called weighted graph.
Graph Representation
• Graph can be represented in two ways
1. Array representation
Array representation
• Graph can be represented using two dimensional array .This is known a adjacency matrix.
Adjacency Matrix
• Example
• Otherwise I(I,J)=0.
Example
Graph Traversal
• A graph traversal means visiting all the nodes of the graph in predefined order.There are two types of
graph traversal.
• Starting from that node all its unvisited adjacent nodes are visited.
• This process will be recursively done until all the nodes are visited.
Algorithm
Algorithm BFS(G)
Step 1:First the starting node of traversal as S.
Step 2: Visit the S and find the adjacent nodes of S.
Step 3:Visit the unvisited adjacent nodes and keep them in a queue for traversing their adjacent nodes.
Step 4:Take nodes from queue one by one and repeat step 2 and step3 for finding its adjacency nodes until
queue become empty.
Step 5: If queue become empty and all the nodes are traversed then stop the process.
Example
• BFS is :ABDCE
• Then another path and so on until all the nodes have been visited.
Algorithm
Void DFS(vertex V)
{
visited[v]=true
For each adjacent to V
If visited[w]=false then
DFS(vertex w)
}
Example
• DFS is :SADBC
Transitive Closure
• Transitive closure of a given graph is calculated using following steps.
Transitive Closure(A+)
Reflexive Transitive Closure(A*)
Connected Components
• If G is a undirected graph then we can determine whether it is connected or not by using DFS or BFS.
Algorithm:
Procedure Comp(G,n)
for i=1 to n do
visited[i]=0
End
For i=1 to n do
if (visited[i]=0)then
call DFS(i)
End
End comp
Example
Spanning Tree
• A connected acyclic graph is called the spanning tree.
• Example
Minimum Cost Spanning Tree(MCST)
• Spanning tree of the smallest weight is called the minimum cost spanning tree.
• In this method edges are added in the non decreasing order of cost and the edges does not create a
cycle.
Example
Algorithm
Algorithm MCST(G)
T=null
While T contain less than n-1 edges do
lowest cost edge (v,w) delete from E
if(V,W) does not create a cycle in T then
add(V,W) to T
else
discard(V,W)
end
Single source shortest path problem
• For a given vertex is called the source in a weighted connected graph. Find the shortest path to all its
other vertex is called the single source shortest path problem.
• Dijikstra’s algorithm is used to find the single source shortest path problem.
• Steps
1. Find the shortest path from the source to a vertex nearest to it and then next nearest and so on.
Example
4 2
1
5 3
B D C
2 6
8
Starting vertex as A.
Step 1:
Vertex known D(V) Comment
A 1 0
B 0 ∞
C 0 2
D 0 1 Next minimum
E 0 ∞
Visit (A,D) Unkown:(B,C,E)
AD=1
Step 2:
Vertex known D(V) Comment
A 1 0
B 0 6
C 0 2 Next minimum
D 1 1
E 0 ∞
Algorithm
Algorithm Dijikstra()
Step 1: Intialize d as infinity
Step 2: Set S as empty
Step 3: Fix the start node as source
Step 4: While there are still vertices in V
i) Sort the vertices V according to the current distance from the source.
(ii) Select the nearest vertex V which has the shortest edge from the source.
(iii) Add the closest vertex V to S
(iv) Update the distance
End dijikstra
All Pairs Shortest path problem
Find the shortest distance from the each vertex to the all other vertices is called the all pairs shortest path
problem.
Floyd’s method is used to solve all pairs shortest path problem.
2
B
A
3
7 6
1
C D
Distance Matrix:
A B C D
A 0 ∞ 3 ∞
B 2 0 ∞ ∞
C ∞ 7 0 1
D 6 ∞ ∞ 0
D(0)
Select First row first column.
Check number and number cross points
A B C D
A 0 ∞ 3* ∞
B 2* 0 ∞* ∞
C ∞ 7 0 1
D 6* ∞ ∞* 0
D(1)
Select second row second column.
Check number and number cross points
A B C D
A 0 ∞ 3 ∞
B 2* 0 5 ∞
C ∞* 7* 0 1
D 6 ∞ 9 0
D(2)
Select Third row Third column.
Check number and number cross points
A B C D
A 0 ∞* 3* ∞*
B 2 0 5* ∞*
C 9 7* 0 1*
D 6 ∞* 9* 0
D(3)
Select Fourth row Fourth column.
Check number and number cross points
A B C D
A 0 10 3 4
B 2 0 5 6
C 9* 7 0 1
D 6 16 9 0
Solution
D(4)
A B C D
A 0 10 3 4
B 2 0 5 6
C 7 7 0 1
D 6 16 9 0
Algorithm
Algorithm allpairs(W[1..n,1..n])
D=W;
For k= 1 to n do
For i= 1 to n do
For j= 1 to n do
D[i,j]=min{D(k-1)[i,j],D(k-1)[i,k]+D(k-1)[k,j]}
Return D
end
----------------------------------------End of Unit-III----------------------------------------------------------