0% found this document useful (0 votes)
22 views

DS Notes Unit-I To 3

1. A data structure is a way of organizing and storing data so it can be accessed efficiently. An algorithm is a set of steps to solve a problem that must be clear, finite, and produce an output. 2. Common data structures include matrices and arrays. A matrix stores data in rows and columns, while an array stores similar data types sequentially in memory locations. 3. Sparse matrices contain many zero values and can be stored efficiently by only storing the non-zero values and their indices to save memory. The transpose of a matrix switches the rows and columns.

Uploaded by

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

DS Notes Unit-I To 3

1. A data structure is a way of organizing and storing data so it can be accessed efficiently. An algorithm is a set of steps to solve a problem that must be clear, finite, and produce an output. 2. Common data structures include matrices and arrays. A matrix stores data in rows and columns, while an array stores similar data types sequentially in memory locations. 3. Sparse matrices contain many zero values and can be stored efficiently by only storing the non-zero values and their indices to save memory. The transpose of a matrix switches the rows and columns.

Uploaded by

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

DATA STRUCTURES

UNIT I

What is Data Structure?


Way of storing and organizing data is called data structure.So that it can be retrieved efficiently.
Algorithm
An Algorithm is a finite set of instruction in which it accomplish a particular task.
Every algorithm must satisfying the following criteria
(i) Input
Algorithm may have zero or more inputs which is supplied by the user.
(ii) Output
The algorithm must be produced atleast one output.
(iii) Definitness
Each instruction in the algorithm must be clear and unambiguous.
(iv) Finitness
Algorithm will terminate after a finite number of steps.
(v) Effectiveness
Every instruction in the algorithm must carried out by the user.

1. Machines for executing algorithms


Based on the machine configuration the algorithm execution is changed.
2. Languages for describing algorithm
Algorithm also based on language design and transaction .[High level language to the
Machine level languages].
3. Foundation of Algorithm
Algorithm analysis also consider minimum number of operations require to perform a
particular task.
4. Analysis of Algorithm
Algorithm performance also based on time and space complexities.
(a) Time complexities
Time efficiency indicates how fast the algorithm runs.
(b) Space Complexity
Space complexity indicates how much extra memory the algorithm needs.

Matrix
Matrix contain m rows and n columns.
Example
-27 3 4
6 8 7
2 1 3

Here m=3 and n=3


The matrix totally contain m*n elements. The above matrix consist of 3 rows and 3
columns that matrix contain mn elements that is 3*3=9 elements.
When m=n (Number of rows=Number of Columns) then we call the matrix as square
matrix.
Transpose of Matrix
The rows and columns of the matrix is changed to obtain the transpose of the matrix.
The transpose of above example matrix is

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

Storing of Sparse Matrix


Store the sparse matrix with zero and non-zero entries take more memory. To avoid this
high memory usage , we can store only non-zero entries in the matrix by using the
formula
A[i, j ,value]
In this A(0,1) of the matrix contains total number of rows , A(0,2) contains total
number of columns and A(0,3) contains total number of non-zero entries . Then we
enter the non-zero entries row by row.
The above sparse matrix is stored in following way
A 1 2 3
0 6 6 8
1 1 1 15
2 1 4 22
3 1 6 -15
4 2 2 11
5 2 3 3
6 3 4 -6
7 5 1 91
8 6 3 28

Transpose of Sparse Matrix


In transpose of a matrix rows and columns are interchanged. The same way also applied
to the sparse matrix.
There are two methods used to find the transpose of sparse matrix.
Method-I
Step:1
In this method for each row I do take the element (i,j,value) and store it in (j,i,value) of
the transpose.
The transpose of above sparse matrix is

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
Q1
For col1 to n do
For p1 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

Where ui=Upper limit


Li=Lower limit
Representation of one dimensional array
Elements : A(1) A(2) A(3) ……….A(i)………..A(u1)
Address : α α +1 α +2………..α +(i−1)………α +(u 1−1)
In one dimensional array element is defined from A(1) to A(u1) where u1 is the upper
limit. Address of the element is measured from α to α +(u 1−1), where α is the address
of the first element.
Address of the ith element is find using the formula α +(i−1).
Address of the last element is find using the formula α +(u 1−1),
Example
Array A={10,20,30,40,50}
A 1 2 3 4 5
Element 10 20 30 40 50
Address 1000 1001 1002 1003 1004

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

In the above example α =1001, u1=3 , u2=3


Address of A[3,2] is find in following way
Here i=3 j=2
Address of A(i,j) is α + ( i−1 ) u2+ ( j−1 )
A[3,2]=1001+(3-1)3+(2-1)
= 1001+2*3+1
=1001+6+1
Address of A[3,2] is=1008
Representation of three or Multi- dimensional array
Three dimensional array is stored in the x,y and z format.
Syntax
(u1,u2,u3)
Where u1,u2 and u3 are limits of x,y,z respectively.Address of the particular element in
three dimensional array is represented in the formula
A(i,j,k) = α + ( i−1 ) u2 u 3+ ( j−1 ) u 3+ ( k−1 )

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
Toptop+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
Itemstack(top)
Toptop-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
Rearrear+1
Q(rear)item
If front=0 then
Front1
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
ItemQ(front)
If(front=rear)then
Frontrear0
Else
Frontfront+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

In circular Queue also we perform two operations. They are


1.Insertion
2. Deletion

Insertion Algorithm
Algorithm CQinsertion(Q,f,r,n,item)
If r=n then
R1
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
yQ(F)
if f=r then
fr0
return(y)
if f=n then
f1
else
ff+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)
Top0 // 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

3. Read B it is also operand then b also added to stack.


B
A
4. Read + it is operator then value of A and B are retrieve from stack and perform
addition at last store the result in top of stack.
5. Read ∞ then identify end is reached so we display the result from top of the stack.
Infix to Postfix Conversion
Example
A*B/C
 In this operators *,/ are equal priority. So we take it from left to right.
 First convert A*B postfix of A*B is AB*
 Equation become AB*/C
 Then it is become AB*C/

There are two methods in infix to postfix conversion


1. Using stack
2. Using built-in-functions.

1. Infix to postfix conversion using stack


Steps
 Read the expression element by element.
 If it is operand then display it otherwise if it is operator then add
to the top of the stack.
 At the end of the expression retrieve the operators one by one
from the stack and display it.
Example
E=A+B*C∞

Next Token Stack Output


None Empty Empty
A - A
+ + A
B + AB
* +* AB
C +* ABC
∞ ABC*+
Postfix form of A+B*C=ABC*+

2.Infix to Postfix conversion using built-in functions


Infix to postfix conversion algorithm use two built-in functions.
 ISP(x)-In stack priority
 ICP(x)-Incoming priority

ISP and ICP values for operators


Symbol ISP ICP
) - -
** 3 4
*,/ 2 2
Binary +,- 1 1
( 0 4

Algorithm
Procedure Postfix(E)
Stack(1)’∞’
Top1
Loop
Xnext_token(E)
Case
:x=’∞’: while top>1 do //empty the stack
Print(stack(top));
Toptop-1
End
Print(‘∞’)
Return
:x is an operand: print(x)
:x=’)’: while stack(top)!= ‘(‘ do
Print(stack(top));toptop-1
End
Toptop-1 // delete ‘)’
:else: while ISP(stack(top))>=ICP(x) do
Print(stack(top));toptop-1;
End
Call Add(x,stack,n,top)) //insert x is stack
End
Forever
End postfix

Multiple Stack and Queues


 In single stack and queue use single memory in the computer.
 In multiple stack is represented using array V[1..M] where M is the maximum
number of stacks.
 V[1] is the stack-1 and V[2] is the stack-2 and so on.
 B[i] is the bottom element of ith stack. And T[i] is the top element of ith stack.
Representation
V
1 2 …………….. M
B[1] T[1]B[2] T[2] B[M] T[M]

Multiple Stack Insertion Algorithm


Procedure Add(i,x)
//i-ith Stack
// x- inserted element
If(T(i) =B(i+1)) then
Call stack_full(i)
T(i)T(i)+1
V[(T(i)] x
End Add
Multiple Stack Deletion Algorithm
Procedure delete(i,x)
If(T(i)=B(i)) then
Call stack_empty(i)
XV[T(i)]
T(i) T(i)-1
End delete

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

A 1001 B 1002 C NULL

Creation of Node
Procedure create(T)
Call getnode(I)
TI;
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
TI
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

Insertion into the middle of the linked list


Ex:
MAT PAT CAT 0
Available Linked List
 We I= insert node OAT into between the node MAT and PAT.
 Here X=MAT
 Link(I)Link(X)

MAT PAT CAT 0


X

OAT

 Link(X)I

MAT PAT CAT 0


X

OAT

 Link(X)I
Result

MAT OAT PAT CAT 0


X

Insert At Last of the Linked List


Available Linked List

MAT PAT CAT 0

X
Insert below node into last of linked list
OAT
I

Link(I)Link(X)

MAT PAT CAT X


OAT 0
I
Link(X)I

MAT PAT CAT OAT 0

Result

MAT PAT CAT OAT 0

Delete node from the Linked List


Procedure Delete(X,Y,T)
// X is the node to be deleted
//Y is node proceeding to X
//T is pointer to linked list
If Y=0 then
TLink(T) //Remove the first node
Link(X)0
Else //Remove middle or last node
Link(Y)Link(X)
Link(X)0
Call Ret(X)
End delete

The above algorithm is used to delete the node from the first,middle and last of the linked list.

Example

Available Linked List

CAT PAT MAT 0

T
Remove the first node CAT
Y=0
X=CAT
TLink(T)

CAT PAT MAT 0


Result

PAT MAT 0

The above example the node CAT is deleted.


Remove Middle node

Available Linked List

CAT PAT MAT 0

T
Remove the middle node PAT.
Y=CAT
X=PAT
Link(Y)Link(X)

MAT 0
CAT PAT

Link(X)0

CAT PAT MAT 0

Result

PAT MAT 0

Remove the Last node

Available Linked List

CAT PAT MAT 0

Remove the last node MAT


Y=PAT
X=MAT
Link(Y)Link(X)

CAT PAT 0 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

T(i) Data Link

Linked Stack Insertion


Algorithm
Procedure Add(i,y)
// i stack
//y-inserted element
Call getnode(x)
Data(x)y
Link(x)T(i)
T(i)x
End

Example
T(i)
x 40

T(i) 30

20

10 0

Linked Stack Deletion


In Linked stack also deletion performed in top of the stack.
Procedure delete(i,y)
If(T(i)=0)then
Print “Stack is empty”
XT(i)
Y=Data(x)
T(i)Link(x)
Call ret(x)
End delete
Example
T(i)
30

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)

Linked Queue Insertion


 In linked queue insertion is performed in rear end of the queue.
Procedure AddQ(i,y)
Call getnode(x)
Data(x)y
Link(y)0
If f(i)=0 then
F(i)R(i)x
Else
Link(R(i))x
R(i)x
end

Example
10 20 30 0

Insert 40 into linked queue


40
X

Result

30 40
10 20

F(i) R(i)

Linked Queue Deletion


 In linked queue deletion is performed in front end of the queue.
Algorithm
Procedure deleteQ(i,y)
If F(i)=0 then
Call “Queue Empty”
Else
XF(i)
YData(x)
F(i)link(x)
Link(x)0
Call RET(x)
End deleteQ
Example

10 20 30 0

F(i) R(i)
Result
10 20 0

Circular Linked List


In linked list if last node point to the first node then it is called circular linked list.
Example

10 20 30 0

Polynomial Addition

General form of polynomial equation is


A(x)=amem+…………….+a1xe1
Normal Process
Example
A=3x14 +2x8 +1
B=8x14 -3x10 +10x6
A+B=11x14 -3x10 +2x8 +10x6 +1
Polynomial Addition using Linked List
Every term in the polynomial equation is represented using nodes. Each node have three fields
1. Coefficient
2. Exponent
3. Link
Co-Efficient Exponent Link

Link part point to the next term of polynomial equations.


Example
A=3x14 +2x8 +1
3 14 2 8 1 0 0

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.

Creation of polynomial node


Procedure attach(k,e,d)
//k-co-efficient
// e-exponent
//d-pointer to last node
Call getnode(I)
Exp(I)E
Coeff(I)k
Link(d)I
AI
End attach
Algorithm
Algorithm addpoly(p1,p2,p3)
Step 1: Create Linked Polynomials
Step 2:Read the coefficients and exponent values of polynomials.
Step 3: Set the pointers P1 and P2 to both polynomials respectively to traverse them.
Step 4: Start from the first node and compare the exponent of the two polynomials.
a) If (p1.exp==p2.exp)
P3.coeff=p1.coeff+p2.coeff
P3.exp=p1.exp
b) If (p1.exp<p2.exp)
P3.coeff=p2.coeff
P3.exp=p2.exp
Else
P3.exp=p1.exp
P3.coeff=p1.coeff
Step 5: Append the remaining nodes of either of the polynomials to the resulted linked list.
Example

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

More on Linked List


In linked list we can also perform the following operations.
1. Concatenation
2. Insertion
3. Finding Length of the linked list
1. Concatenation
Concatenation operation combine the two linked list and give the resulted linked list.
Algorithm
Procedure concatenate(X,Y,Z)
// X={a1,a2……….am}
// Y={b1,b2……….bn} m,n>=0
//Z={a1,a2…..am,b1,b2….bn}
ZX
If(X=0) then
ZY;
Return;
If(Y=0) then
ZX;
PX;
While (link(P)<>0) do
Plink(P);
End
Link(P)Y
End concatenate
Example
X=
x1 x2
x3 0

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)
PX;
Q0;
While(P<>0) do
RQ;
QP;
PLink(P);
Link(Q)R;
End
XQ;
End invert
Example
X=
x1 x2 x3 0

X’=
x3 x2
x1 0

Finding Length of the Circular Linked List


We can also find the length of the circular linked list using below algorithm.
Algorithm
Procedure Length(A)
i0
if(A<>0) then
ptrA;
repeat
ii+1;
ptrlink(ptr);
until ptrA;
return i;
end Length
Example
X=
x1 x2 x3 0

 i=1 when ptrx1


 i=2 when ptrx2
 i=3 when ptrx3
 Length of the circular linked list=3

Sparse Matrix Using Linked List


 Sparse matrix contains many zero entries for save the memory we represent only non-
zero elements using linked list.In this representation of sparse matrix each node can be
divided into five parts.
 Syntax:
Down Row Column Right
Value
 Down field will be used to link the non-zero element in the same column.
 Right field will be used to link the non-zero element in the same row.
 Row-Row number
 Column-Column number
 Value-Value of the non-zero entry
 Every row and column linked with head node.
Example:
0 0 10
15 0 0
0 20 0
Linked List representation of sparse matrix

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

 Data : Original Data value


 Plink:point to Previous node address
 Nlink: Point to next node address
Example
Address
1000 1020 1040 1060

Null A 1020 100 B 1040 102 C 1060 104 D Null


0 0 0

 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]
Newnodedata=value
Newnodeplink=null
Newnodenlink=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
lastnodenlink=newnode
newnodeplink=lastnode
c) Lastnode=newnode
Goto(a)
end createDlist;

Insertion into Doubly Linked List


The new node can be inserted into the following three places of the doubly linked list.
 Inserting as first node
 Inserting as last node
 Inserting as intermediate node
Inserting as first node
 Allocating memory for the new node.
 Assign value to the data field and assign null to the both link fields.
 Nlink of the new node point to the head node.
 Plink of the head node point to the new node.
 Set new node as head node.
Algorithm
Algorithm DLinsertfirst(Head node)
Step 1: Allocate memory for the new node.
Step 2:
newnodeData=value
newnodePlink=Null
newnodeNlink=Null
Step 3:[If the list is empty]
If [ Head =Null]
Set Head=newnode
Stop
Step 4: [if list is not empty]
NewnodeNlink=Head
HeadPlink=newnode
Head=newnode
End DLinsertfirst;

Example

Null A1 A B Null

Newnode Last
Head

Inserting as Last node


 Allocating memory for the new node.
 If the list is empty then make the new node node has first node and head node.
 If the list is not empty then goto the last node and insert the new node after the last node.
 Set the last nodes Nlink point to the new node and in new node’s Plink point to the last node
 Set new node as last node.

Algorithm
Algorithm DLinsertlast(Head:Node)
Step 1: Create new node by allocating memory.
Step 2: [Intialize the new node]
Newnodedata=value
NewnodePlink=Null
NewnodeNlink=Null
Step 3: [if the list is empty]
If (Head=Null) then
Set Head=newnode
Stop
Step 4: [ if list is not empty]
LastNlink=newnode
Newnodeplink=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

Inserting as Intermediate node


 Allocating memory for the new node.
 Assign values to the data field of the new node.
 Make the Nlink field of the A point to the new node.
 Set the Plink field of the node B point to the new node.
 Assign Plink of newnode point to node A and Nlink of new node point to the node B.

Algorithm
Algorithm DLinsertintermediate(Head : Node)
Step 1: Creating new node by allocating memory.
Step 2: [Read data value]
Newnodedata=value
NewnodePlink=Null
NewnodeNlink=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=ANlnk
ANlink=newnode
BPlink=newnode
NewnodePlink=A
NewnodeNlink=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

Deletion From Doubly Linked List


Deletion of a node from the doubly linked list can be done on three different places such as
 Deleting the first node
 Deleting the last node
 Deleting the intermediate node
Deleting the First node
 Make sure that the list is not empty.
 Move the head pointer to the second node and make the plink of the second node as null.
 Free the memory occupy by the first node.
Algorithm
Algorithm deletefirstDL()
Step 1:
If( Head=Null) then
Print(“List is empty”)
Stop
Step 2:

If(List is not empty)

Assign Head=FirstNlink

FirstNlink=Null
SecondPlink=Null

Step 3:De-allocate the space occupied by the deleted node.

End deletefirstDL;

Example

Null X Y1 Y Z Null
Head

First Last

After Deletion

Null X Null Y1 Y Z Null


Head Last
Result

Null Y1 Y Z Null
Head Last

Deleting the Last node

 Make sure that the list is not empty.


 Move the list of fix the last node.
 Set the Nlink of last node and Plink of deleted node to be null.
 Free the memory occupied by the node.

Algorithm

Algorithm DeletelastDL()

Step 1:

If ( Head=Null) then
Print(“List is empty”)

Stop

Step 2:

If(List is not empty)

Delnode=Lastnode

Assign Last=DelnodePlink

DelnodePlink=Null

LastNlink=Null

Step 3: Deallocate the space occupied by the deleted node.

DeletelastDL;

Example

Null X Y1 Y Z Null
Head

First Last

After Deletion

Null X Null Y1 Y Null Z Null


Head
Last(Delnode)
Result

Null X Y1 Y Null
Head Last
Deleting the Intermediate node

 Make sure that the list is not empty.

 Make the Nlink of node A point to node B and Plink of node B point to node A.

 Free the node between A and B.

Algorithm

Algorithm deleteintermediateDL()

Step 1:

If ( Head=Null) then

Print(“List is empty”)

Stop

Step 2:

If (List is not empty)

Repeat for each node in the list and check

If(nodedata=deldata) then

Begin

A=DelnodePlink

B=DelnodeNlink

ANlink=B

BPlink=A

DelnodeNlink=Null

DelnodePlink=Null

End
Else

Node=nodenlink

Until end of list

Step 3: Release the memory occupied by the delete node.

End deleteintermediateDL;

Example

Null X Y1 Y Z Null
Head

Last

After Deletion

Null X Null Y1 Null Y Null Null Z Null

Head A Delnode B Last

Result

Null X Y1 Z Null
Head Last

Advantages of Doubly Linked List

 Efficient memory initialization

 Easy accessibility of node.


 Traversal time is reduced.

 No disconnectivity.

Disadvantages

 Using of two pointers more memory space is required.


Dynamic storage Management

 In multiprogramming computer several programming reside in the computer memory at the same

time.

 Different programs have different memory requirements.

 When the execution of the program is completed the allocated memory is released.

 In dynamic memory storage management memory requirements not known in advance.Memory is

allocated only in run time.

Example

Available memory 100000 words.Available programs 5.Their memory requirements given below

Program Memory requirement

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.

10000 15000 6000 8000 20000 41000


P1 P2 P3 P4 P5 Free
 After P1 and P4 are completed.

15000 6000 20000


10000 8000 41000
 Free list can be represented using linked list. In that linked list each node contain two fields.
1. Size : Size of free memory
2. Link : Link to next free memory location
 Free list can be started with head node.
Example
Head 10000 8000 41000 Null

Re-Allocating free memory location


 Free memory locations are reassigned using two allocation strategies.
1. First fit strategy
2. Best fit strategy

1. First Fit Strategy


Search the list to find the free block if size of block is>=n then allocating that block for the
new node. This strategy is called first fit strategy.
Algorithm for First fit strategy
Procedure FirstFit()
// n-Requested size
//p-Address block
// Al-Available space list
Plink(AL)
QAL
While p<>0 do
If (size(p)>=n) then
Size(p)=size(p)-n
If(size(p)=0) then
Link(q)link(p)
Else
p=p+size(p)
return
qp
plink(p)
end
end firstfit
Problems in First Fit Strategy
There are two major problems in first fit strategy.
1. Some smaller nodes are not used for allocation.
2. Always search begins from the front of the search list. If some small nodes are available in the
first of the list then it is not necessary to examine the remaining part of the list.
These problems are avoided by using the storage release method.

Storage Release Method


In this method all the small nodes are combined into larger one.
Algorithm
Step 1: If the address of the returned block is greater than the variable starting point then start
the search at the variable starting point.
Else
Start the search at the list head.
Step 2: Find the predecessor or successor of the returned block in the free list.
If allocated block is closer to the successor then combine the block with its successor.
Step 3: If an allocated block exist between freed block and its predecessor then combine the
block with its predecessor.
Boundary Tag Method
In this method free list can be represented using the following node representation.
Flag Size Successor Predecessor

Flag : It is used to indicate whether the block is allocated or not.


1 means Block is allocated.
0 means not allocated.
Size : Size of the block
Successor : Point to the successor
Predecessor: Point to the predecessor
There are 4 cases in boundary tag method.
Case 1: Block B is free but its neighbors A & C are already allocated then freed block is
simply placed into the free list.
Case 2: if block A is already free and block B is freed now then A & B is combined and added
the free list.
Case 3:if block C is free and B is now free then B & C are combined and added to the free list.
Case 4: If block A nd C are already free and B is ready to allocate then A,B & c are combined
and added to the free list.

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

Not allocated Allocated


(ii) Tag Field
 If tag field is 0 then it contains atomic information otherwise tag field is 1 then it contains non-atomic
information and also it contains two link fields such as Dlink and Rink.
Algorithm
Step 1: Initially all the nodes marked as 0.
Step 2: Traverse the node one by one that node is called x.
Step 3: if mark(x)=0 and tag(x)=0 then set mark(x)=1
Step 4: if mark(x)=0 and tag(x)=1 then use either Dlink or Rlink to traverse the node and use the
stack and mark node one bye one as 1.
Disadvantage
Mark1 algorithm need additional space for maintain stack.

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

Tasks in Storage Compaction


 Storage compaction perform three tasks
1. Determine new addresses for nodes in used.
2. Update all the links of nodes are in use.
3. Relocate nodes to new addresses.
Important Questions
One mark
1. Define linked list.
2. Single linked list contain ---------- and ----------- part.
3. In polynomial addition node is divided into---------parts.
4. Stack is represented using linked list is called-------
5. Queue is represented using linked list is called----
6. Define doubly linked list.
7. Define first fit strategy.
8. Finding the free block whose size is is as close to n but not less than n is called ----
strategy.
9. Larger blocks are split into sub blocks then each sub block is called----
10. The process of collecting all unused nodes and returning them into available space list
is called------------
11. In garbage collection which algorithm is best-------------

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

(i) Linear Data structure


In linear data structure there is a linear relationship between adjacent elements.
Example
Array,Stack,Queue and Linked list
(ii) Non-Linear data structure
In non linear data structure data are represented using hierarchical relationship.
Example
Trees and graphs
Trees
Definition of trees
A tree is a non-linear data structure represents hierarchical relationship between individual data items.
Tree satisfied the following requirements
 Tree has a special data item called as root of the tree.
 All remaining data items are partitioned into number of subset called as sub trees.
Example
Tree Terminologies
1. Root
The root is the first and top most node in the hierarchical arrangement of data items.
Example
In the above diagram A is the root node.
2. Node
Each data item in the tree is called a node.
Example
From the above diagram A,B,C,D,E,F,G,H,I,J are nodes.
3. Degree of a node
The degree of a node is the number of subtrees of a node in a given tree.
Example
In the above diagram
Degree(A)=2
Degree(B)=2
Degree(C)=2
4. Degree of a Tree
The degree of a tree is the maximum degree of any node in the tree.
Example
In the above diagram the degree of tree is 2.
5. Terminal node
A node with degree zero is called a terminal node or leaf node.
Example
In the above diagram terminal nodes are D,F,H,I and J.
6. Non terminal nodes
Any node whose degree is non-zero is called non-terminal nodes
Example
In the above diagram non terminal nodes are A,B,C, E,G
7. Sibilings
The children nodes of a same parent node are called sibilings.
Example
In the above diagram Sibiling(A)=B,C
Sibiling(B)=D,E
8. Level
The entire tree structure is leveled in such a way that the root node is always at level-0 then its
immediate children are at level-1 and so on.
Example
In the above diagram total levels are 4.
9. Edge
Edge is a line which connects two adjacent nodes of a tree.The line drawn from one node to another
node is called edge.
10. Path
A path is a sequence of consecutive edges from the source node to the destination node.

Example
The above diagram
Path(A-C) is ABC
11. Depth or Height
The length of any longest path of the tree is called depth of the tree.
Example
The above diagram
Depth(AD)=3
Depth(AH)=4
Depth(AF)=3
Depth(AI)=4
Depth(AJ)=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

Binary tree Representation

Binary tree can be represented in two ways


1. Linear representation(Using Array)
2. Linked representation(Using pointer)

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

BT(0) BT(1) BT(2) BT(3) BT(4)

Father of a particular node can be find using the formula Fahter(n)=floor(n-1)/2


Example
Father(B)=floor(1-1)/2
=0
Father(B)=A
Left child of a particular node is find using the formula
Lchild(n)=2n+1

Example
Lchild(A)=2(0)+1
=1
Lchild(A)=B

Right child of a particular node is find using the formula


Rchild(n)=2n+2
Example
Rchild(A)=2(0)+2
=2
Rchild(A)=C
Disadvantages of Linear representation
 When using array for skewed binary tree memory wastage will result.
 Insertion and deletion in array is difficult.

Linked List representation of Binary tree

In linked representation of binary tree each node contain 3 fields


LCHILD DATA RCHILD

Example
Linked Representation

B C

NULL D NULL NUL E NULL NULL F NULL NULL G NULL


 L
The left and right child of a terminal node is null.
 Non terminal nodes are called as internal nodes and terminal nodes are called as external nodes.

Advantages
Insertion and deletion is very easy.
Disadvantages
More memory space is required to store pointers.

Binary Tree Traversal


 Traversal is most important operation performed on the binary tree.
 Binary tree traversal means visiting each node in the tree exactly once.
 There are 3 types of traversal in the binary tree.
1. Preorder traversal
2. Postorder traversal
3. Inorder traversal

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

Threaded Binary Tree


 In linked representation of binary tree null links are replaced by pointers called threads.
 In threaded binary tree null link of the left child point to the predecessor of the inorder traversal and
null link of the right child point to the successor of the inorder traversal.

Example

B C

Inorder traversal :BAC


Threaded Binary Tree
A
Headnode Headnode

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.

Equal operation on Binary tree


• Equal operation return false if binary tree S and T are not equal otherwise it return true.
• Algorithm
Procedure Equal(S,T)
ans=false
case
:S=0 and T=0: ans=false
:S<>0 and T <> 0:
if(Data(S)=Data(T) then
ans=equal(Lchild(S),Lchild(T)
if(ans) then
ans=Equal(Rchild(S),Rchild(T))
end
return (ans)
End Equal

Example

Both are equal so it return


true.

Propositional Calculus
• Binary tree also used to represent propositional calculus.
• Ex: (X1^X2)V(X1^X3)
Tree Format

Binary Tree Representation of trees


• The normal tree can be converted into binary tree using two steps.
1. It is represented in the format of
2. Then the representation can be converted into binary tree using tilde(~) operation.~ operation means
rotate node into 45 Degree clock wise.Then horizontal line become left child and Vertical line
become right child.
Example

Convert Forest to Binary Tree


• Forest also converted into binary tree using following steps

1. Each of the tree in the forest is converted into binary tree.

2. All the binary trees are combined together through the sibling field of the root node.
Example
FOREST

Tree1 To Binary Tree


Tree2 To Binary Tree
Tree3 To Binary Tree
Forest to Binary Tree

Counting Binary Tree


• We can determine the number of distinct binary trees using n nodes.

• n is the number of nodes

• If n=0 or n=1 then only one binary tree is possible.

• If n=2 then we have two different binary trees.


When n=2 possible binary trees

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

8. Degree of directed graph


• The degree of directed graph is divided into two types.
1. Indegree
2. Outdegree
1.Indegree
The number of edges coming into the vertex V is called the indegree of that vertex.
Indegree(A)=1
2.Outdegree
The number of edges coming out of the vertex V is called outdegree of that vertex.
Ex: Outdegree(A)=2
9.Complete Graph
• A graph is said to be fully connected if there is a path from every vertex to every other 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

2. Adjacency List representation

Array representation
• Graph can be represented using two dimensional array .This is known a adjacency matrix.

• In adjacency matrix A[I,J]=1 if there is an edge from Vi to Vj.

• A[I,J]=0 if there is no edge between Vi to Vj.

Adjacency Matrix

Adjacency List Representation


• A graph can be represented using linked list called adjacency list representation.

• Example

Incidence Matrix Representation


• The incidence matrix I is represented for G(V,E).

• If I(I,J)=1 if there is an incidence of edge ei on Vj.

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

1. Breath first traversal(BFS)

2. Depth first traversal(DFS)

Breath First Traversal


• In this method a node from the graph is selected randomly as the start position.

• 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

Depth First Traversal


• In depth first traversal visit path from starting node to ending node.

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

Step 1: Find the adjacency matrix of the given graph is called A.


Step 2:From the adjacency matrix find the transitive closure called A+.
if there is a path from I to j then A+(I,j)=1 otherwise A+(I,j)=0.
Step 3:Find the reflexive transitive closure from the transitive closure it is called A*.
If there path length>=0 then A*(I,j)=1 otherwise A*(I,J)=0.
Example
Adjacency Matrix-A

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 the above example

• Weight of spanning tree1 is 14

• Weight of spanning tree2 is 13

• Weight of spanning tree3 is 11

• Weight of spanning tree4 is 10

• So Minimum Cost spanning tree is Tree4.

Minimum Cost Spanning tree


Kruskal’s Method
• Kruskal’s method is used to find the minimum cost spanning tree from the given graph.

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

2. Every time new vertex is added to shortest path.

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)
AD=1

Step 2:
Vertex known D(V) Comment
A 1 0
B 0 6
C 0 2 Next minimum
D 1 1
E 0 ∞

Visit (A,D,C) Unkown:(B,E)


AC=2
Step 3:
Vertex known D(V) Comment
A 1 0
B 0 6 Next minimum
C 1 2
D 1 1
E 0 8

Visit (A,D,C,B) Unkown:(E)


ADB=6
Step 4:
Vertex known D(V) Comment
A 1 0
B 1 6
C 1 2
D 1 1
E 0 8 Next minimum

Visit (A,D,C,B,E) Unkown:(-)


ACE=8
Solution
Shortest path to B is=6
Shortest path to C is=2
Shortest path to D is=1
Shortest path to E is=8

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

You might also like