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

24BTPCCX22_ Data Structure Notes_FINAL

Uploaded by

dhyeypatel1092
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

24BTPCCX22_ Data Structure Notes_FINAL

Uploaded by

dhyeypatel1092
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Introduction to Data Structure Lecture 01

 Computer is an electronic machine which is used for data processing and manipulation.
 When programmer collects such type of data for processing, he would require to store all of them in
computer’s main memory.
 In order to make computer work we need to know
o Representation of data in computer.
o Accessing of data.
o How to solve problem step by step.
 For doing this task we use data structure.

What is Data Structure?


 Data structure is a representation of the logical relationship existing between individual elements of
data.
 Data Structure is a way of organizing all data items that considers not only the elements stored but also
their relationship to each other.
 We can also define data structure as a mathematical or logical model of a particular organization of
data items.
 The representation of particular data structure in the main memory of a computer is called as storage
structure.
 The storage structure representation in auxiliary memory is called as file structure.
 It is defined as the way of storing and manipulating data in organized form so that it can be used
efficiently.
 Data Structure mainly specifies the following four things
o Organization of Data
o Accessing methods
o Degree of associativity
o Processing alternatives for information
 Algorithm + Data Structure = Program
 Data structure study covers the following points
o Amount of memory require to store.
o Amount of time require to process.
o Representation of data in memory.
o Operations performed on that data.
Classification of Data Structure Lecture 02

DATA
STRUCTURE

PRIMITIVE NON
PRIMITIVE

INTEGER FLOATING CHARACTER POINTER ARRAY LIST FILE


POINT

LINEAR LIST NON


LINEAR LIST

STACK QUEUE GRAPH TREE

Data Structures are normally classified into two broad categories

1. Primitive Data Structure

2. Non-primitive data Structure

Data types
A particular kind of data item, as defined by the values it can take, the programming language used, or
the operations that can be performed on it.

Primitive Data Structure


 Primitive data structures are basic structures and are directly operated upon by machine instructions.
 Primitive data structures have different representations on different computers.
 Integers, floats, character and pointers are examples of primitive data structures.
 These data types are available in most programming languages as built in type.
o Integer: It is a data type which allows all values without fraction part. We can use it for whole numbers.
o Float: It is a data type which use for storing fractional numbers.
o Character: It is a data type which is used for character values.
Pointer: A variable that holds memory address of another variable are called pointer.

Non primitive Data Type


 These are more sophisticated data structures.
 These are derived from primitive data structures.
 The non-primitive data structures emphasize on structuring of a group of homogeneous or heterogeneous
data items.
 Examples of Non-primitive data type are Array, List, and File etc.
 A Non-primitive data type is further divided into Linear and Non-Linear data structure
o Array: An array is a fixed-size sequenced collection of elements of the same data type.
o List: An ordered set containing variable number of elements is called as Lists.
o File: A file is a collection of logically related information. It can be viewed as a large list of records
consisting of various fields.

Linear data structures


 A data structure is said to be Linear, if its elements are connected in linear fashion by means of logically or in
sequence memory locations.
 There are two ways to represent a linear data structure in memory,
o Static memory allocation
o Dynamic memory allocation
 The possible operations on the linear data structure are: Traversal, Insertion, Deletion, Searching, Sorting
and Merging.
 Examples of Linear Data Structure are Stack and Queue.
 Stack: Stack is a data structure in which insertion and deletion operations are performed at one end only.
o The insertion operation is referred to as ‘PUSH’ and deletion operation is referred to as ‘POP’ operation.
o Stack is also called as Last in First out (LIFO) data structure.
 Queue: The data structure which permits the insertion at one end and Deletion at another end, known as
Queue.
o End at which deletion is occurs is known as FRONT end and another end at which insertion occurs is
known as REAR end.
o Queue is also called as First in First out (FIFO) data structure.

Nonlinear data structures


 Nonlinear data structures are those data structure in which data items are not arranged in a sequence.
 Examples of Non-linear Data Structure are Tree and Graph.
 Tree: A tree can be defined as finite set of data items (nodes) in which data items are arranged in branches
and sub branches according to requirement. o Trees represent the hierarchical relationship between
various elements.
o Tree consist of nodes connected by edge, the node represented by circle and edge lives connecting to
circle.
 Graph: Graph is a collection of nodes (Information) and connecting edges (Logical relation) between nodes.
o A tree can be viewed as restricted graph.
o Graphs have many types:
 Un-directed Graph
 Directed Graph
 Mixed Graph
 Multi Graph
 Simple Graph
 Null Graph
 Weighted Graph

Difference between Linear and Non Linear Data Structure


Linear Data Structure Non-Linear Data Structure
Every item is related to its previous and next time. Every item is attached with many other items.
Data is arranged in linear sequence. Data is not arranged in sequence. Data items
can be traversed in a single run. Data cannot be traversed in a single run.
Eg. Array, Stacks, linked list, queue. Eg. tree, graph.
Implementation is easy. Implementation is difficult.

Operation on Data Structures


Design of efficient data structure must take operations to be performed on the data structures into account. The
most commonly used operations on data structure are broadly categorized into following types

1. Create
The create operation results in reserving memory for program elements. This can be done by declaration
statement. Creation of data structure may take place either during compile-time or run-time. malloc()
function of C language is used for creation.

2. Destroy
Destroy operation destroys memory space allocated for specified data structure. free() function of C
language is used to destroy data structure.

3. Selection
Selection operation deals with accessing a particular data within a data structure.
4. Updation
It updates or modifies the data in the data structure.

5. Searching
It finds the presence of desired data item in the list of data items, it may also find the locations of all
elements that satisfy certain conditions.

6. Sorting
Sorting is a process of arranging all data items in a data structure in a particular order, say for example,
either in ascending order or in descending order.

7. Merging
Merging is a process of combining the data items of two different sorted list into a single sorted list.

8. Splitting
Splitting is a process of partitioning single list to multiple list.

9. Traversal
Traversal is a process of visiting each and every node of a list in systematic manner.

Time and space analysis of algorithms


Algorithm

 An essential aspect to data structures is algorithms.

 Data structures are implemented using algorithms.

 An algorithm is a procedure that you can write as a C function or program, or any other language.

 An algorithm states explicitly how the data will be manipulated.

Algorithm Efficiency

 Some algorithms are more efficient than others. We would prefer to choose an efficient algorithm, so it
would be nice to have metrics for comparing algorithm efficiency.

 The complexity of an algorithm is a function describing the efficiency of the algorithm in terms of the
amount of data the algorithm must process.

 Usually there are natural units for the domain and range of this function. There are two main complexity
measures of the efficiency of an algorithm

 Time complexity

 Time Complexity is a function describing the amount of time an algorithm takes in terms of the
amount of input to the algorithm.
 "Time" can mean the number of memory accesses performed, the number of comparisons between
integers, the number of times some inner loop is executed, or some other natural unit related to the
amount of real time the algorithm will take.

 Space complexity

 Space complexity is a function describing the amount of memory (space) an algorithm takes in terms
of the amount of input to the algorithm.

 We often speak of "extra" memory needed, not counting the memory needed to store the input itself.
Again, we use natural (but fixed-length) units to measure this.

 We can use bytes, but it's easier to use, say, number of integers used, number of fixed-sized structures,
etc. In the end, the function we come up with will be independent of the actual number of bytes
needed to represent the unit.

 Space complexity is sometimes ignored because the space used is minimal and/or obvious, but
sometimes it becomes as important an issue as time.

Worst Case Analysis


In the worst case analysis, we calculate upper bound on running time of an algorithm. We must know the case
that causes maximum number of operations to be executed. For Linear Search, the worst case happens when
the element to be searched is not present in the array. When x is not present, the search () functions compares
it with all the elements of array [] one by one. Therefore, the worst case time complexity of linear search would
be.

Average Case Analysis


In average case analysis, we take all possible inputs and calculate computing time for all of the inputs. Sum all
the calculated values and divide the sum by total number of inputs. We must know (or predict) distribution of
cases. For the linear search problem, let us assume that all cases are uniformly distributed. So we sum all the
cases and divide the sum by (n+1).

Best Case Analysis


In the best case analysis, we calculate lower bound on running time of an algorithm. We must know the case
that causes minimum number of operations to be executed. In the linear search problem, the best case occurs
when x is present at the first location. The number of operations in worst case is constant (not dependent on n).
So time complexity in the best case would be.
Explain Array in detail
One Dimensional Array
 Simplest data structure that makes use of computed address to locate its elements is the
onedimensional array or vector; number of memory locations is sequentially allocated to the vector.
 A vector size is fixed and therefore requires a fixed number of memory locations.
 Vector A with subscript lower bound of “one” is represented as below….

L0  L0 is the address of the first word allocated to the first element of


vector A.
 C words are allocated for each element or node
 The address of Ai is given equation Loc (Ai) = L0 + C (i-1)
L0 + (i-1)C
A [i]  Let’s consider the more general case of representing a vector A
whose lower bound for it’s subscript is given by some variable b.
The location of Ai is then given by Loc (Ai) = L0 + C (i-b)

Two Dimensional Array
 Two dimensional arrays are also called table or matrix, two dimensional arrays have two subscripts
 Two dimensional array in which elements are stored column by column is called as column major matrix
 Two dimensional array in which elements are stored row by row is called as row major matrix
 First subscript denotes number of rows and second subscript denotes the number of columns
 Two dimensional array consisting of two rows and four columns as above Fig is stored sequentially by
columns : A [ 1, 1 ], A [ 2 , 1 ], A [ 1 , 2 ], A [ 2 , 2 ], A [ 1 , 3 ], A [ 2 , 3 ], A [ 1, 4 ], A [ 2, 4 ]
 The address of element A [ i , j ] can be obtained by expression Loc (A [ i , j ]) = L0 + (j-1)*2 + i-1
 In general for two dimensional array consisting of n rows and m columns the address element A [ i , j ] is
given by Loc (A [ i , j ]) = L0 + (j-1)*n + (i – 1)
 In row major matrix, array can be generalized to arbitrary lower and upper bound in its subscripts,
assume that b1 ≤ I ≤ u1 and b2 ≤ j ≤u2

b1, b2 b1, u2
[1,1][1,2] [1,3] [ 1 ,m ] col 1 col 2 col 3 col 4

[2,1][2,2] [2,3] [2m] row 1 [ 1 , 1 ] [1,2] [1,3] [1,4]


row 2 [ 2 , 1 ] [2,2] [2,3] [2,4]
[n,1][n,2] [n,3] [n,m]
u1, b2

Row major matrix Column major matrix


No of Columns = m = u2 – b2 + 1

 For row major matrix : Loc (A [ i , j ]) = L0 + ( i – b1 ) *(u2-b2+1) + (j-b2)


Applications of Array
1. Symbol Manipulation (matrix representation of polynomial equation)
2. Sparse Matrix

Symbol Manipulation using Array


 We can use array for different kind of operations in polynomial equation such as addition, subtraction,
division, differentiation etc…
 We are interested in finding suitable representation for polynomial so that different operations like
addition, subtraction etc… can be performed in efficient manner
 Array can be used to represent Polynomial equation

 Matrix Representation of Polynomial equation


Y Y2 Y3 Y4
X XY X Y2 X Y3 X Y4
2 2 2 2 2 3
X X Y X Y X Y X2 Y4
X3 X3 Y X3 Y2 X3 Y3 X3 Y4
4
X X4 Y X4 Y2 X4 Y3 X4 Y4

e.g. 2x2+5xy+Y2 e.g. x2+3xy+Y2+Y-X


is represented in matrix form as below is represented in matrix form as below
Y Y2 Y3 Y4 Y Y2 Y3 Y4
0 0 1 0 0 0 0 1 0 0
X 0 5 0 0 0 X -1 3 0 0 0
2 2
X 2 0 0 0 0 X 1 0 0 0 0
X3 0 0 0 0 0 X3 0 0 0 0 0
4 4
X 0 0 0 0 0 X 0 0 0 0 0

 Once we have algorithm for converting the polynomial equation to an array representation and another
algorithm for converting array to polynomial equation, then different operations in array (matrix) will be
corresponding operations of polynomial equation

What is sparse matrix? Explain


 An mXn matrix is said to be sparse if “many” of its elements are zero.
 A matrix that is not sparse is called a dense matrix.
 We can device a simple representation scheme whose space requirement equals the size of the
nonzero elements.
 Example:-
o The non-zero entries of a sparse matrix may be mapped into a linear list in row-major order.
o For example the non-zero entries of 4X8 matrix of below fig.(a) in row major order are 2, 1, 6, 7,
3, 9, 8, 4, 5

0 0 0 2 0 0 10
0 6 0 0 7 0 03
0 0 0 9 0 8 00
0 4 5 0 0 0 00
Fig (a) 4 x 8 matrix

Terms 0 1 2 3 4 5 6 7 8
Row 1 1 2 2 2 3 3 4 4
Column 4 7 2 5 8 4 6 2 3
Value 2 1 6 7 3 9 8 4 5
Fig (b) Linear Representation of above matrix

 To construct matrix structure we need to record


(a) Original row and columns of each non zero entries
(b) No of rows and columns in the matrix
 So each element of the array into which the sparse matrix is mapped need to have three fields: row,
column and value
 A corresponding amount of time is saved creating the linear list representation over initialization of two
dimension array.

0 0 6 0 9 0 0
A= 2 0 0 7 8 0 4
10 0 0 0 0 0 0
0 0 12 0 0 0 0
0 0 0 0 0 0 0
0 0 0 3 0 0 5

 Here from 6X7=42 elements, only 10 are non zero. A[1,3]=6, A[1,5]=9, A[2,1]=2, A[2,4]=7, A[2,5]=8,
A[2,7]=4, A[3,1]=10, A[4,3]=12, A[6,4]=3, A[6,7]=5.
 One basic method for storing such a sparse matrix is to store non-zero elements in one dimensional
array and to identify each array elements with row and column indices fig (c).

ROW COLUMN A
1 1 3 6
2 1 5 9
3 2 1 2
4 2 4 7
5 2 5 8
6 2 7 4
7 3 1 10
8 4 3 12
9 6 4 3
10 6 7
5
Fig (c )
COLUMN A
1 3 6
ROW 2 5 9
1 1 3 1 2
2 3 4 4 7
3 7 5 5 8
4 8 6 7 4
5 0 7 1 10
6 9 8 3 12
9 4 3
10 7 5
ROW NO First Column
for row no COLUMN NO

Fig(d)

 A more efficient representation in terms of storage requirement and access time to the row of the
matrix is shown in fid (d). The row vector changed so that its ith element is the index to the first of the
column indices for the element in row I of the matrix.

Linked Representation of Sparse matrix


Typical node to represent non-zero element is

Row Column Value Pointer To


Number Number Next Node

1 3 6 1 5 9 2 1 2 2 4 7

2 5 8 2 7 4 3 1 10 4 3 12

6 4 3 6 7 5 NULL
Write algorithms for Stack Operations – PUSH, POP, PEEP
 A linear list which allows insertion and deletion of an element at one end only is called stack.
 The insertion operation is called as PUSH and deletion operation as POP.
 The most and least accessible elements in stack are known as top and bottom of the stack respectively.
 Since insertion and deletion operations are performed at one end of a stack, the elements can only be
removed in the opposite orders from that in which they were added to the stack; such a linear list is
referred to as a LIFO (last in first out) list.

 A pointer TOP keeps track of the top element in the stack. Initially, when the stack is empty, TOP has a
value of “one” and so on.
 Each time a new element is inserted in the stack, the pointer is incremented by “one” before, the
element is placed on the stack. The pointer is decremented by “one” each time a deletion is made from
the stack.

Applications of Stack
 Recursion
 Keeping track of function calls
 Evaluation of expressions
 Reversing characters
 Servicing hardware interrupts
 Solving combinatorial problems using backtracking.

Procedure : PUSH (S, TOP, X)


 This procedure inserts an element x to the top of a stack which is represented by a vector S containing N
elements with a pointer TOP denoting the top element in the stack.
1. [Check for stack overflow]
If TOP ≥ N
Then write (‘STACK OVERFLOW’)
Return
2. [Increment TOP]
TOP ←TOP + 1
3. [Insert Element]
S[TOP] ←X
4. [Finished]
Return

Function : POP (S, TOP)


 This function removes the top element from a stack which is represented by a vector S and returns this
element. TOP is a pointer to the top element of the stack.

1. [Check for underflow of stack]


If TOP = 0
Then Write (‘STACK UNDERFLOW ON POP’)
Take action in response to underflow
Return
2. [Decrement Pointer]
TOP ← TOP – 1
3. [Return former top element of stack]
Return (S[TOP + 1])

Function : PEEP (S, TOP, I)


 This function returns the value of the ith element from the TOP of the stack which is represented by a vector
S containing N elements. The element is not deleted by this function.

1. [Check for stack Underflow]


If TOP - I +1 ≤ 0
Then Write (‘STACK UNDERFLOW ON PEEP’)
Take action in response to Underflow Exit
2. [Return Ith element from top of the stack
Return (S[TOP – I + 1])
Write an algorithm to change the ith value of stack to value X
PROCEDURE : CHANGE (S, TOP, X, I)
 This procedure changes the value of the Ith element from the top of the stack to the value containing in X.
Stack is represented by a vector S containing N elements.

1. [Check for stack Underflow]


If TOP – I + 1 ≤ 0
Then Write (‘STACK UNDERFLOW ON CHANGE’)
Return
2. [Change Ith element from top of the stack]
S[TOP – I + 1] ← X
3. [Finished]
Return
1. [Save N and return Address]
CALL PUSH (A, TOP, TEMP_REC)
2. [Is the base criterion found?]
If N=0
then FACTORIAL 1
GO TO Step 4
Else PARAM N-1
ADDRESS Step 3
GO TO Step 1
3. [Calculate N!]
FACTORIAL N * FACTORIAL
4. [Restore previous N and return address]
TEMP_RECPOP(A,TOP)
(i.e. PARAMN, ADDRESSRET_ADDR)
GO TO ADDRESS

Give difference between recursion and iteration


Iteration Recursion
In iteration, a problem is converted into a train of Recursion is like piling all of those steps on top of
steps that are finished one at a time, one after each other and then quashing them all into the
another solution.
With iteration, each step clearly leads onto the In recursion, each step replicates itself at a smaller
next, like stepping stones across a river scale, so that all of them combined together
eventually solve the problem.
Any iterative problem is solved recursively Not all recursive problem can solved by iteration
It does not use Stack It uses Stack
Write an algorithm to convert infix expression to postfix expression.

Symbol Input precedence Stack precedence Rank function R


function F function G
+, - 1 2 -1
*, / 3 4 -1
^ 6 5 -1
Variables 7 8 1
( 9 0 -
) 0 - -

Algorithm : REVPOL
 Given an input string INFIX containing an infix expression which has been padded on the right with ‘)’ and
whose symbol have precedence value given by above table, a vector S used as a stack and a NEXTCHAR
which when invoked returns the next character of its argument. This algorithm converts INFIX into reverse
polish and places the result in the string POLISH. The integer variable TOP denotes the top of the stack.
Algorithm PUSH and POP are used for stack manipulation. The integer variable RANK accumulates the rank
of expression. Finally the string variable TEMP is used for temporary storage purpose.
Trace the conversion of infix to postfix form in tabular form.
(i) ( A + B * C / D - E + F / G / ( H + I ) )

Input Symbol Content of stack Reverse polish Rank


( 0
( (( 0
A (( 0
+ ((+ A 1
B ((+B A 1
* ((+* AB 2
C ((+*C AB 2
/ ((+/ ABC* 2
D ((+/D ABC* 2
- ((- ABC*D/+ 1
E ((-E ABC*D/+ 1
+ ((+ ABC*D/+E- 1
F ((+F ABC*D/+E- 1
/ ((+/ ABC*D/+E–F 2
G ((+/G ABC*D/+E–F 2
/ ((+/ ABC*D/+E–FG/ 2
( ((+/( ABC*D/+E–FG/ 2
H ((+/(H ABC*D/+E–FG/ 2
+ ((+/(+ ABC*D/+E–FG/H 3
I ((+/(+I ABC*D/+E–FG/H 3
) ((+/ ABC*D/+E–FG/HI+ 3
) ( ABC*D/+E–FG/HI+/+ 1
) ABC*D/+E–FG/HI+/+ 1

Postfix expression is: A BC*D/+E–FG/HI+/+


(ii) ( A + B ) * C + D / ( B + A * C ) + D

Input Symbol Content of stack Reverse polish Rank


( 0
( (( 0
A ((A 0
+ (( + A 1
B ((+B A 1
) ( AB+ 1
* (* AB+ 1
C (*C AB+ 1
+ (+ AB+C* 1
D (+D AB+C* 1
/ (+/ AB+C*D 2
( (+/( AB+C*D 2
B (+/(B AB+C*D 2
+ (+/(+ AB+C*DB 3
A (+/(+A AB+C*DB 3
* (+/(+* AB+C*DBA 4
C (+/(+*C AB+C*DBA 4
) (+/ AB+C*DBAC*+ 3
+ (+ AB+C*DBAC*+/+ 1
D (+D AB+C*DBAC*+/+ 1
) AB+C*DBAC*+/+D+ 1

Postfix expression is: AB+C*DBAC*+/+D+


Evaluate (i): 5 4 6 + * 4 9 3 / + *
Empty Stack Read Operator +, Read Operator *,
pop two values pop two values
from stack opn2 = from stack opn2 =
Read and push 6, opn1 = 4, and 10, opn1 = 5, and
operands 5, 4, 6 push the answer 10 push the answer 50
6
4 10
5 5 50 Read and
push
operands
4, 9, 3

Read Operator *, Read Operator +, Read Operator /, 3


pop two values pop two values
3 pop two values
from stack opn2 = from stack opn2 = 9
from stack opn2 =
7, opn1 = 50, and 7 3, opn1 = 4, and 4 3, opn1 = 9, and
push the answer
4
push the answer 7 push the answer 3
350 350 50 50 50
Poped value 350 is the answer

Evaluate (ii) : * 7 5 2 + * 4 1 1 + / -
Empty Stack Read Operator +, Read Operator *,
pop two values pop two values
from stack opn2 = from stack opn2 =
Read and push 2, opn1 = 5, and 7, opn1 = 7, and
operands 7, 5, 2 push the answer 7 push the answer 49
2
5 7
7 5 49 Read and
push
operands
4, 1, 1

Read Operator - , Read Operator /, Read Operator +, 1


pop two values pop two values
2 pop two values
from stack opn2 = from stack opn2 = 1
from stack opn2 =
2, opn1 = 49, and 2 2, opn1 = 4, and 4 1, opn1 = 1, and
push the answer 47
4
push the answer 2 push the answer 2
47 49 49 49
Poped value 47 is the answer
Consider the following arithmetic expression P, written in postfix notation.
Translate it in infix notation and evaluate. P: 12, 7, 3, -, /, 2, 1, 5, +, *, +
Same Expression in infix notation is : ( 12 / ( 7 – 3 ) ) + ( ( 5 + 1 ) * 2 )

Empty Stack Read Operator -, Read Operator /,


pop two values pop two values
from stack opn2 = from stack opn2 =
Read and push 3, opn1 = 7, and 4, opn1 = 12, and
operands 12, 7, 3 push the answer 4 push the answer 3
3
7 4
12 12 3 Read and
push
operands
2, 1, 5

Read Operator +, Read Operator *, Read Operator +, 5


pop two values pop two values
6 pop two values
from stack opn2 = from stack opn2 = 1
from stack opn2 =
12, opn1 = 3, and 12 6, opn1 = 2, and 2 5, opn1 = 1, and
push the answer 15
2
push the answer 12 push the answer 6
15 3 3 3
Poped value 15 is the answer

Explain Difference between Stack and Queue.


Stack Queue
A Linear List Which allows insertion or deletion of A Linear List Which allows insertion at one end and
an element at one end only is called as Stack deletion at another end is called as Queue
Since insertion and deletion of an element are Since insertion and deletion of an element are
performed at one end of the stack, the elements performed at opposite end of the queue, the
can only be removed in the opposite order of elements can only be removed in the same order of
insertion. insertion.
Stack is called as Last In First Out (LIFO) List. Queue is called as First In First Out (FIFO) List.
The most and least accessible elements are called Insertion of element is performed at FRONT end
as TOP and BOTTOM of the stack and deletion is performed from REAR end
Example of stack is arranging plates in one above Example is ordinary queue in provisional store.
one.
Insertion operation is referred as PUSH and Insertion operation is referred as ENQUEUE and
deletion operation is referred as POP deletion operation is referred as DQUEUE
Function calling in any languages uses Stack Task Scheduling by Operating System uses queue
Explain following:
(i) Queue (ii) Circular Queue (iii) DQUEUE (iv) Priority Queue
(i) Queue
o A linear list which permits deletion to be performed at one end of the list and insertion at the other
end is called queue. o
The information in such a list is processed FIFO (first in first out) of FCFS (first come
first served) pattern.
o Front is the end of queue from that deletion is to be performed.
o Rear is the end of queue at which new element is to be inserted.
o The process to add an element into queue is called Enqueue
o The process of removal of an element from queue is called Dequeue.
o The familiar and traditional example of a queue is Checkout line at Supermarket Cash Register
where the first person in line is usually the first to be checkedout.

Front

Deletion Insertion

Rear

(ii) Circular Queue


o A more suitable method of representing simple queue which prevents an excessive use of memory
is to arrange the elements Q[1], Q[2]….,Q[n] in a circular fashion with Q[1] following Q[n], this is
called circular queue o
In a standard queue data structure re-buffering problem occurs for each dequeue operation. To
solve this problem by joining the front and rear ends of a queue to make the queue as a circular
queue
o Circular queue is a linear data structure. It follows FIFO principle.
o In circular queue the last node is connected back to the first node to make a circle.
o Circular linked list fallow the First In First Out principle
o Elements are added at the rear end and the elements are deleted at front end of the queue
o Both the front and the rear pointers points to the beginning of the array.
o It is also called as “Ring buffer”.
(iii) Dequeue
o A dequeue (double ended queue ) is a linear list in which insertion and deletion are performed from
the either end of the structure.
o There are two variations of Dqueue
 Input restricted dqueue- allows insertion at only one end
 Output restricted dqueue- allows deletion from only one end
o Such a structure can be represented by following fig.

Front

Deletion Insertion

Insertion Deletion

Rear

(iv) Priority Queue


o A queue in which we are able to insert remove items from any position based on some property
(such as priority of the task to be processed) is often referred as priority queue.
o Below fig. represent a priority queue of jobs waiting to use a computer.
o Priorities of 1, 2, 3 have been attached with jobs of real time, online and batch respectively.
Therefore if a job is initiated with priority i,it is inserted immediately at the end of list of other jobs
with priorities i. Here jobs are always removed from the front of queue
Task Identification
R1 R2 … Ri-1 O1 O2 … Oj-1 B1 B2 … Bk-1 …
1 1 … 1 2 2 … 2 3 3 … 3 …
Priority
Ri Oj Bk
Fig (a) : Priority Queue viewed as a single queue with insertion allowed at any position.
Priority 1
R1 R2 … Ri-1 … Ri

Priority 2
O1 O2 … Oj-1 … Oj
Priority 3
B1 B2 … Bk-1 … Bk

Fig (b) : Priority Queue viewed as a Viewed as a set of queue


Write algorithms of basic primitive operations for Queue
Procedure: QINSERT_REAR (Q, F, R, N,Y)
 Given F and R pointers to the front and rear elements of a queue respectively. Queue Q consisting of N
elements. This procedure inserts Y at rear end of Queue.

1. [Overflow]
IF R >= N
Then write (‘OVERFLOW’)
Return
2. [Increment REAR pointer]
RR+1
3. [Insert element ]
Q[R]  Y
4. [Is front pointer properly set]
IF F=0
Then F  1
Return

Function: QDELETE_FRONT (Q, F, R)


 Given F and R pointers to the front and rear elements of a queue respectively. Queue Q consisting of N
elements. This function deleted and element from front end of the Queue.

1. [Underflow]
IF F= 0
Then write (‘UNDERFLOW’)
Return(0) (0 denotes an empty Queue)
2. [Decrement element]
Y  Q[F]
3. [Queue empty?]
IF F=R
Then F R 0
Else F F+1 (increment front pointer)
4. [Return element]
Return (Y)
Then F  1
Return
Linear Data Structure and their linked storage representation.
There are many applications where sequential allocation method is unacceptable because of following
characteristics

 Unpredictable storage requirement


 Extensive manipulation of stored data

The linked allocation method of storage can result in both efficient use of computer storage and computer time.

 A linked list is a non-sequential collection of data items.


 The concept of a linked list is very simple, for every data item in the linked list, there is an associated
pointer that would give the memory allocation of the next data item in the linked list.
 The data items in the linked list are not in a consecutive memory locations but they may be anywhere in
memory.
 Accessing of these data items is easier as each data item contains within itself the address of the next
data item.

10 next 20 next 30 next 40 null

A Linked List

What is linked list? What are different types of linked list? OR


Write a short note on singly, circular and doubly linked list. OR
Advantages and disadvantages of singly, circular and doubly linked list.
• A linked list is a collection of objects stored in a list form.
• A linked list is a sequence of items (objects) where every item is linked to the next.
• A linked list is a non-primitive type of data structure in which each element is dynamically allocated and
in which elements point to each other to define a linear relationship.
• Elements of linked list are called nodes where each node contains two things, data and pointer to next
node. •
Linked list require more memory compared to array because along with value it stores pointer to next
node.
• Linked lists are among the simplest and most common data structures. They can be used to implement
other data structures like stacks, queues, and symbolic expressions, etc…
Node
// C Structure to represent a node
struct node
info link
{
int info
struct node *link
Data Pointer to
};
next node

Operations on linked list


• Insert
o Insert at first position
o Insert at last position
o Insert into ordered list
• Delete
• Traverse list (Print list)
• Copy linked list

Types of linked list


Singly Linked List • It is basic type of linked list.
• Each node contains data and pointer to next node.
• Last node’s pointer is null.
• Limitation of singly linked list is we can traverse only in one direction, forward direction.

A next B next C next D null

Singly Linked List

Circular Linked List


• Circular linked list is a singly linked list where last node points to first node in the list.
• It does not contain null pointers like singly linked list.
• We can traverse only in one direction that is forward direction.
• It has the biggest advantage of time saving when we want to go from last node to first node, it
directly points to first node. •
A good example of an application where circular linked list should be used is a timesharing problem
solved by the operating system.
A next B next C next D next

Circular Linked List

Doubly Linked list


• Each node of doubly linked list contains data and two pointers to point previous (LPTR) and next
(RPTR) node.

Node // C Structure to represent a node


struct node
LPTR info RPTR {
int info
struct node *lptr;
Pointer to struct node *rptr;
Pointer to Data
next node };
previous node

• Main advantage of doubly linked list is we can traverse in any direction, forward or reverse.
• Other advantage of doubly linked list is we can delete a node with little trouble, since we have
pointers to the previous and next nodes. A node on a singly linked list cannot be removed unless we
have the pointer to its predecessor.
• Drawback of doubly linked list is it requires more memory compared to singly linked list because we
need an extra pointer to point previous node. •
L and R in image denote left most and right most nodes in the list.
• Left link of L node and right link of R node is NULL, indicating the end of list for each direction.

null A next prev B next prev C null

Doubly Linked List


L R

Discuss advantages and disadvantages of linked list over array.

Advantages of an array
1. We can access any element of an array directly means random access is easy
2. It can be used to create other useful data structures (queues, stacks)
3. It is light on memory usage compared to other structures

Disadvantages of an array
1. Its size is fixed
2. It cannot be dynamically resized in most languages
3. It is hard to add/remove elements
4. Size of all elements must be same.
5. Rigid structure (Rigid = Inflexible or not changeable)

Advantages of Linked List


1. Linked lists are dynamic data structures: That is, they can grow or shrink during execution of a
program.
2. Efficient memory utilization: Here memory is not pre-allocated. Memory is allocated whenever it is
required. And it is deallocated (free) when it is no longer needed.
3. Insertion and deletions are easier and efficient: Linked list provide flexibility in inserting a data item
at a specified position and deletion of a data item from the given position.
4. Elements of linked list are flexible: It can be primary data type or user defined data types

Disadvantages of Linked List


1. Random access is not allowed. We have to access elements sequentially starting from the first node.
So we cannot do binary search with linked lists.
2. It cannot be easily sorted
3. We must traverse 1/2 the list on average to access any element
4. More complex to create than an array
5. Extra memory space for a pointer is required with each element of the list

What are the advantages and disadvantages of stack and queue


implemented using linked list over array?
Advantages and disadvantages of stack & queue implemented using linked list over array is described below,

Insertion & Deletion Operation


 Insertion and deletion operations are known as push and pop operation in stack and as insert and
delete operation in queue.
 In the case of an array, if we have n-elements list and it is required to insert a new element between
the first and second element then n-1 elements of the list must be moved so as to make room for
the new element.
 In case of linked-list, this can be accomplished by only interchanging pointers.
 Thus, insertion and deletions are more efficient when performed in linked list then array.
Searching a node
 If a particular node in a linked list is required, it is necessary to follow links from the first node
onwards until the desired node is found.
 Where as in the case of an array, directly we can access any node

Join & Split


 We can join two linked list by assigning pointer of second linked list in the last node of first linked
list.
 Just assign null address in the node from where we want to split one linked list in two parts.
 Joining and splitting of two arrays is much more difficult compared to linked list.

Memory
 The pointers in linked list consume additional memory compared to an array

Size
 Array is fixed sized so number of elements will be limited in stack and queue.
 Size of linked list is dynamic and can be changed easily so it is flexible in number of elements

Insertion and deletion operations in Array and Linked-List


X1 X2 X3 X4 X5 X6

Array Insert Y at location 2. You have to move X2, X3,…, X6

X1 Y X2 X3 X4 X5 X6

X1 X2 X3 X4

Insert Y at location 2. Just change two pointers


Linked-
List X1 X2 X3 X4

Y
Write following algorithms for singly linked list.
1) Insert at first position
2) Insert at last position

Few assumptions,

 We assume that a typical element or node consists of two fields namely; an information field called
INFO and pointer field denoted by LINK. The name of a typical element is denoted by NODE.

Node
// C Structure to represent a node
struct node
info link
{
int info
struct node *link
Data Pointer to
};
next node
Function: INSERT( X, First )
Given X, a new element and FIRST is a pointer to the first element of a linked linear list. Typical node contains
INFO and LINK fields. AVAIL is a pointer to the top element of the availability stack; NEW is a temporary pointer
variable. This function inserts a new node at the first position of linked list. This function returns address of
FIRST node.

1 [Underflow?]
IF AVAIL = NULL
Then Write (“Availability Stack Underflow”) Return(FIRST)

2 [Obtain address of next free Node]


NEWAVAIL

3 [Remove free node from Availability Stack]


AVAILLINK(AVAIL)

4 [Initialize fields of new node and its link to the list]


INFO (NEW)  X
LINK (NEW)  FIRST

5 [Return address of new node]


Return (NEW)

When INSERT is invoked it returns a pointer value to the variable FIRST

FIRST  INSERT (X, FIRST)


Function: INSEND( X, First ) (Insert at end)
Given X, a new element and FIRST is a pointer to the first element of a linked linear list. Typical node contains
INFO and LINK fields. AVAIL is a pointer to the top element of the availability stack; NEW is a temporary pointer
variable. This function inserts a new node at the last position of linked list. This function returns address of FIRST
node.

1 [Underflow?]
IF AVAIL = NULL
Then Write (“Availability Stack Underflow”) Rn(FIRST)

2 [Obtain address of next free Node]


NEWAVAIL

3 [Remove free node from Availability Stack]


AVAILLINK(AVAIL)

4 [Initialize field of NEW node]


INFO (NEW)  X
LINK (NEW)  NULL

5 [Is the list empty?]


If FIRST = NULL
then Return (NEW)

6 [Initialize search for a last node]


SAVE  FIRST

7 [Search for end of list]


Repeat while LINK (SAVE) ≠ NULL
SAVE  LINK (SAVE)

8 [Set link field of last node to NEW)


LINK (SAVE)  NEW

9 [Return first node pointer]


Return (FIRST)

When INSERTEND is invoked it returns a pointer value to the variable FIRST

FIRST  INSERTEND (X, FIRST)


Discuss following

1. Graph
 A graph G consist of a non-empty set V called the set of nodes (points, vertices) of the
graph, a set E which is the set of edges and a mapping from the set of edges E to a set of
pairs of elements of V.
 It is also convenient to write a graph as G=(V,E).
 Notice that definition of graph implies that to every edge of a graph G, we can associate a
pair of nodes of the graph. If an edge X Є E is thus associated with a pair of nodes (u,v)
where u, v Є V then we says that edge x connect u and v.

2. Adjacent Nodes
 Any two nodes which are connected by an edge in a graph are called adjacent node.

3. Directed & Undirected Edge


 In a graph G=(V,E) an edge which is directed from one end to another end is called a
directed edge, while the edge which has no specific direction is called undirected edge.

4. Directed graph (Digraph)


 A graph in which every edge is directed is called directed graph or digraph.

5. Undirected graph
 A graph in which every edge is undirected is called undirected graph.

6. Mixed Graph
 If some of the edges are directed and some are undirected in graph then the graph is called
mixed graph.

7. Loop (Sling)
 An edge of a graph which joins a node to itself is called a loop (sling).

8. Parallel Edges
 In some directed as well as undirected graphs, we may have certain pairs of nodes joined by
more than one edges, such edges are called Parallel edges.

9. Multigraph
 Any graph which contains some parallel edges is called multigraph.

10. Weighted Graph


 A graph in which weights are assigned to every edge is called weighted graph.
11. Isolated Node
 In a graph a node which is not adjacent to any other node is called isolated node.

12. Null Graph


 A graph containing only isolated nodes are called null graph. In other words set of edges in
null graph is empty.

13. Path of Graph


 Let G=(V, E) be a simple digraph such that the terminal node of any edge in the sequence is
the initial node of the edge, if any appearing next in the sequence defined as path of the
graph.

14. Length of Path


 The number of edges appearing in the sequence of the path is called length of path.

15. Degree of vertex


 The no of edges which have V as their terminal node is call as indegree of node V
 The no of edges which have V as their initial node is call as outdegree of node V
 Sum of indegree and outdegree of node V is called its Total Degree or Degree of vertex.

16. Simple Path (Edge Simple)


 A path in a diagraph in which the edges are distinct is called simple path or edge simple.

17. Elementary Path (Node Simple)


 A path in which all the nodes through which it traverses are distinct is called elementary
path.

18. Cycle (Circuit)


 A path which originates and ends in the same node is called cycle (circuit).

19. Directed Tree


 A directed tree is an acyclic digraph which has one node called its root with in degree 0,
while all other nodes have in degree 1.
 Every directed tree must have at least one node.
 An isolated node is also a directed tree.

20. Terminal Node (Leaf Node)


 In a directed tree, any node which has out degree 0 is called terminal node or leaf node.

21. Level of Node


 The level of any node is the length of its path from the root.
22. Ordered Tree
 In a directed tree an ordering of the nodes at each level is prescribed then such a tree is
called ordered tree.

23. Forest
 If we delete the root and its edges connecting the nodes at level 1, we obtain a set of
disjoint tree. A set of disjoint tree is a forest.

24. M-ary Tree


 If in a directed tree the out degree of every node is less than or equal to m then tree is
called an m-ary tree.

25. Full or Complete M-ary Tree


 If the out degree of each and every node is exactly equal to m or 0 and their number of
nodes at level i is m(i-1) then the tree is called a full or complete m-ary tree.

26. Positional M-ary Tree


 If we consider m-ary trees in which the m children of any node are assumed to have m
distinct positions, if such positions are taken into account, then tree is called positional
mary tree.

27. Height of the tree


 The height of a tree is the length of the path from the root to the deepest node in the tree.

28. Binary tree


 If in a directed tree the out degree of every node is less than or equal to 2 then tree is called
binary tree.

29. Strictly binary tree


 A strictly binary tree (sometimes proper binary tree or 2-tree or full binary tree) is a tree in
which every node other than the leaves has two children.

30. Complete binary tree


 If the out degree of each and every node is exactly equal to 2 or 0 and their number of
nodes at level i is 2(i-1) then the tree is called a full or complete binary tree.

31. Sibling
 Siblings are nodes that share the same parent node.

32. Binary search tree


 A binary search tree is a binary tree in which each node possessed a key that satisfy the
following conditions
1. All key (if any) in the left sub tree of the root precedes the key in the root.
2. The key in the root precedes all key (if any) in the right sub tree.
3. The left and right sub tree sub trees of the root are again search trees.

33. Height Balanced Binary tree (AVL Tree)


 A tree is called AVL (height balance binary tree), if each node possesses one of the following
properties
1. A node is called left heavy if the longest path in its left sub tree is one longer then
the longest path of its right sub tree.
2. A node is called right heavy if the longest path in the right sub tree is one longer
than path in its left sub tree.
3. A node is called balanced, if the longest path in both the right and left sub tree are
equal.

Explain the Preorder, Inorder and Postorder traversal techniques of the


binary tree with suitable example.

 The most common operations performed on tree structure is that of traversal. This is a procedure by
which each node in the tree is processed exactly once in a systematic manner.
 There are three ways of traversing a binary tree.
1. Preorder Traversal
2. Inorder Traversal
3. Postorder Traversal

A Preorder traversal : A B C D E F G

Inorder traversal : C B A E F D G
B D Postorder traversal : C B F E G D A

Converse Preorder traversal : A D G E F B C


C E G
Converse Inorder traversal : G D F E A B C

Converse Postorder traversal : G F E D C B A


Fig. 1.1
F
Construct a tree for the given Inorder and Postorder traversals

Inorder :DGBAHEICF
Postorder : G D B H I E F C A

D G B H E I C F

B C

D G H E I F

B C

D E F

G H I

8
Postorder : C B E H G I F D A
Inorder :BCAEDGHFI

B C E D G H F I

B D

C E G H F I

B D

C E F

G H I

B D

C E F

G I

H
Construct a tree for the given Inorder and Preorder traversals

Preorder : G B Q A C K F P D E R H
Inorder : Q B K C F A G P E D H R

Q B K C F A P E D H R

B P

Q K C F A D E R H

B P

Q A D

E R H
K C F

B P

Q A D

C E R

K F H
Create a binary search tree for the following data :
50 ,25 ,75, 22,40,60,80,90,15,30

50

25 75

22 40 80
60

15 30 90

Construct binary search tree for the following data and find its Inorder,
Preorder and Postorder traversal
10,3,15,22,6,45,65,23,78,34,5

10

3 15

6 22

5
45

23 65

34 78

Preorder : 10, 3, 6, 5, 15, 22, 45, 23, 34, 65, 78


Inorder : 3, 5, 6, 10, 15, 22, 23, 34, 45, 65, 78
Postorder : 5, 6, 3, 34, 23, 78, 65, 45, 22, 15, 10
What is the meaning of height balanced tree? How rebalancing is done in
height balanced tree.

A tree is called AVL (height balance binary tree), if each node possesses one of the following properties

1. A node is called left heavy if the longest path in its left sub tree is one longer then the longest path of its
right sub tree.
2. A node is called right heavy if the longest path in the right sub tree is one longer than path in its left sub
tree.
3. A node is called balanced, if the longest path in both the right and left sub tree are equal.

If tree becomes unbalanced by inserting any node, then based on position of insertion, we need to rotate the
unbalanced node. Rotation is the process to make tree balanced

1) Insertion into Left sub-tree of nodes Left child – Single Right Rotation
2) Insertion into Right sub-tree of node’s Left child – Left Right Rotation
3) Insertion into Left sub-tree of node’s Right child – Right Left Rotation
4) Insertion into Right sub-tree of node’s Right child – Single Left Rotation

1) Insertion into Left sub-tree of nodes Left child – Single Right Rotation
If node becomes unbalanced after insertion of new node at Left sub-tree of nodes Left child, then we need
to perform Single Right Rotation for unbalanced node.

Right Rotation
a. Detach leaf child’s right sub-tree
b. Consider leaf child to be the new parent
c. Attach old parent onto right of new parent
d. Attach old leaf child’s old right sub-tree as leaf sub-tree of new right child

Critical Node J K

Right J
K Z X
Rotation

X Y N Y Z

N
Critical Node 13 7
Steps of 13
7 15 Right 5
Rotation

5 10 3 10 15

7
7

5 13
5 13

3 10 15

3 10 15

2) Insertion into Right sub-tree of node’s Left child – Left Right Rotation
If node becomes unbalanced after insertion of new node at Right sub-tree of node’s Left child, then we need
to perform Left Right Rotation for unbalanced node.

Leaf rotation of leaf child followed by right rotation of parent

J J Y

Y Z K J
K Z
Left Right
Rotation of K Rotation of J
X Y K n X n Z

n X

3) Insertion into Left sub-tree of node’s Right child – Right Left Rotation
If node becomes unbalanced after insertion of new node at Left sub-tree of node’s Right child, then we
need to perform Right Left Rotation for unbalanced node.

Single right rotation of right child followed by left rotation of parent


Unbalanced node
X X Y

T1 Right T1 Y Left
Z
Rotation of Z Rotation of X X Z
T2
Y T4 Z

T1 T2 T3 T4
T3 T4
T2 T3

4) Insertion into Right sub-tree of node’s Right child – Single Left Rotation
If node becomes unbalanced after insertion of new node at Right sub-tree of nodes Right child, then we
need to perform Single Left Rotation for unbalanced node.

Left Rotation
a. Detach right child’s leaf sub-tree
b. Consider right child to be new parent
c. Attach old parent onto left of new parent
d. Attach old right child’s old left sub-tree as right sub-tree of new left child

Unbalanced node
X
Y
T1
Y Leaf
T3
Rotation of X X

T2 T3
T1 T2
n

Example

50 Unbalanced node 70 70

40 70 50 80 50 80

90

60 80 40 90 40 60

90 60
12. Construct AVL Search tree by inserting following elements in order of
their occurrence 6, 5, 4, 3, 2, 1

1 2 3 4
Insert 6 Insert : 5 Insert : 4 Insert : 3
Right
6 6 6 5 5
F F Rotate 6 F
F F
: 5 : 5 : 4 i i
6 4 6
\ F \ F \ : n n
F : F
D : D 4 : D \ a a
: 3 \ :
F \ F F \ F D l l
\ : D \
S D S : D S F M D M
6\ 5 \ F D
\ F \ F \ S a a
F S
S D D D D Insert : 2F
D Insert : S1 \ t S F \ t S
F \ F 5 F \ F 5 D e e
\ S D 5 \
D S F S D S F F r Righ
S D F Fr
t \ D
F F 3F i 6\ F F 3 i S 6 i i
F D S 6F
i S : i n FD S i : n F F a Rotate 4 a
S F F n FS
n 2 F \ n a4 :F F n 2 \ a4 i : l
F 3S i al :F
a : i D a l: \S i a : D l: n \ F
i n lF
l M l \ M :F \i
l 1 \ n FRight \ DF n F \ a D : n a M: n
M aD M D aD l F \ 2 \i D
M : D a SRotate 5 Fi a S a Dn l a\ Fa
\ a tF a F tF M S D :
a \ Fl Sn l \ l Fa M tD Sl
eS a \ F \
t D S M D3t eS \a M t S D M Sl a eF \M
D
e F \ a FF e r\ Dl a e \ F r\ t D S
a \M t rS Da
F
r S D2t Si r iD FM t r D S iD e F \
t a e i\ Ft
5 aF r S D S D
i \ F: e Fni aF Sa e i F F e Ft r aD Se
: \
a D S\r i a a lS Ft r a S i lS i F F
r Se i lF Fr
1 \ D
l F: FDi n4l l FF i6e i l F n FF a i S
i a FS
: D :i l n F F Fr i
F S i Fa aMF :i nFr a F i a a i l :F na
\ F S
: F nSl l\a : \n a:i l : n l \n F a i
l F \i
D D \ SD F na al
\ i a\F M t a l\a F \ a M D
a : l n F : Dn lF
Assignment: F \ i al
D n l D: aFeD Fl MDl : D l a Fl \ M a
: \ Fa
S D lF
n Construct M:
 Define
F a height S F binary
MF\ of tthe
r
F
SM atree. Define
\ F M balanced
height t SM tree
D awithl its advantages. a height
Sl
\ binary F\ tree) \ a M: D a\
balanced
S l e\i S (AVL
aSD tree a tS: for the S a datae42,06,54,62,88,50,22,32,12,33
D following \a F t M
D F \M
D theF AVLDsearch S tree\ by inserting \the following elements a\ tD
 Construct
\ M tF ra \ D t e F t r D
t S e inathe order ofltheir occurrence. 64,
Da 1,
F tD S eF
44,
D 26,
F 13, 110, F D85 FF
S 98,
i rD S D e i Fe \ r t M
t
aS e i l e S eF \ F rS
S i a
F t rn\ aF F Sr iF \ F r a Sr D i e
\ rS D Se i\
F F n t
S e i aD l : S Fi aS D S i l Fi F a r
D i\ F Fr aD
i i a e
F r al F F\ F ia lF\ F F a F ia S l i
F aD S i lF
n n l r
i ia l MS : Di n l FiD S i l : n
l F F a S lF F na FS
a M i
n a FaF \F n aF :nF F n F \ aF i : l
F i al :F
l l a al a FS
a : i D : \aS i a : D l: n \
l
V1 V4
V1 V2 V3 V4
V1 0 1 0 1 V2
1 0 0 0 V3
1 1 0 1 V4
0 1 00
V2 V3

A digraph and its adjacency matrix

 We can extend the idea of matrix representation to multigraph and weighted graphs. In the case of
multigraph or weighted graph we write aji = w, where aij denotes either the multiplicity or the
weight of the edge.

Path matrix
 An entry of 1 in the ith row and jth column of A shows the existence of an edge (v i, vj), that is a path
of length 1 from vi to vj.
( )
 Let denote the elements of A2 by aij(2). Then {∑
 (2)
Therefore aij is equal to the number of different paths of exactly length 2 from vi to vj.
 Similarly element in ith row and jth column of A3 gives number of paths of exactly length 3 from vi to
v j.

1 1 000 1 1 01 1 2 01
2
A = 1 011 3
A = 1 1 00 4
A = 1 1 01
2 01 2 2 0 1 0 2 3 0 2 1
1 1 00 1 01 1 00

Different path matrices

16. Which are the basic traversing techniques of the Graph? Write the
algorithm of them.

 Most graph problems involve traversal of a graph. Traversal of a graph means visit each node exactly
once.
 Two commonly used graphs traversal techniques are
1. Depth First Search (DFS)
2. Breadth First Search (BFS)
Depth First Search (DFS)
 It is like preorder traversal of tree.
 Traversal can start from any vertex vi
 Vi is visited and then all vertices adjacent to vi are traversed recursively using DFS

1
DFS (G, 1) is given by

a) Visit (1)
2 5
3 4 b) DFS (G, 2)
DFS (G, 3)
DFS (G, 4)
6 7 DFS (G, 5)

DFS traversal of given graph is:


8
1, 2, 6, 3, 8, 7, 4, 5
Graph G

 Since graph can have cycles, we must avoid re-visiting a node. To do this when we visit a vertex V,
we marks it visited as visited should not be selected for traversal.
Procedure : DFS (vertecx V)

This procedure traverse the graph G in DFS manner. V is a starting vertex to be explored. S is a
Stack, visited[] is an array which tells you whether particular vertex is visited or not. W is a adjacent
node of vertex V. PUSH and POP are functions to insert and remove from stack respectively.

1. [Initialize TOP and Visited]


visited[]  0
TOP  0
2. [Push vertex into stack]
PUSH (V)
3. [Repeat while stack is not empty]
Repeat step 3 while stack is not empty
v  POP()
if visited[v] is 0
then visited [v]  1
for all W adjacent to v
if visited [w] is 0
then PUSH (W)
end for
end if
Breadth First Search (BFS)
 This methods starts from vertex v0
 V0 is marked as visited. All vertices adjacent to v0 are visited next
 Let vertices adjacent to v0 are v1, v2, v3, v4
 v1, v2, v3 and v4 are marked visited.
 All unvisited vertices adjacent to v1, v2, v3, v4 are visited next.
 The method continuous until all vertices are visited
 The algorithm for BFS has to maintain a list of vertices which have been visited but not explored for
adjacent vertices. The vertices which have been visited but not explored for adjacent vertices can be
stored in queue.
 Initially the queue contains the starting vertex.
 In every iteration, a vertex is removed from the queue and its adjacent vertices which are not visited
as yet are added to the queue.
 The algorithm terminates when the queue becomes empty.
1
Graph G

2 5
3 4
BFS traversal of given graph is:
1 | 2, 3, 4, 5 | 6, 7 | 8

6 7

8
Procedure : BFS (Vertex V)

This procedure traverse the graph G in BFS manner. V is a starting vertex to be explored. Q is a
queue, visited[] is an array which tells you whether particular vertex is visited or not. W is a adjacent
node of vertex V.
1. Initialize Q
2. [Marks visited of V as 1]
visited [v] 1
3. [Add vertex v to Q]
InsertQueue(V)
4. [Repeat while Q is not empty]
Repeat while Q is not empty
v  RemoveFromQueue()
For all vertices W adjacent to v
if visited[w] is 0
then visited[w] 1
InsertQueue(w)

17. What is spanning tree?

 A Spanning tree of a graph is an undirected tree consisting of only those edges necessary to connect all
the nodes in the original graph
 A spanning tree has the properties that
o For any pair of nodes there exists only one path between them
o Insertion of any edge to a spanning tree forms a unique cycle
 The particular Spanning for a graph depends on the criteria used to generate it.
 If DFS search is use, those edges traversed by the algorithm forms the edges of tree, referred to as
Depth First Spanning Tree.
 If BFS Search is used, the spanning tree is formed from those edges traversed during the search,
producing Breadth First Search Spanning tree.
V0

V1 V2

V3 V4 V5 V6

V7

V0
V0

V1 V2
V1 V2

V3 V4 V5 V6
V3 V4 V5 V6

V7
V7

DFS Spanning Tree BFS Spanning Tree

Consider the graph shown in Fig Find depth-first and breadth first
traversals of this graph starting at A

B C

E
D
F
A A

B C B C

E E
D D
F F

DFS : A B D C F E BFS : A B C D F E
Define spanning tree and minimum spanning tree. Find the minimum
spanning tree of the graph shown in Fig.

A 5
4
3 E
B Using Prim’s Algorithm:
6
2 5 6 7 Let X be the set of nodes explored, initially X = { A }

C D
1

Step 1: Taking minimum weight edge of all Adjacent Step 2: Taking minimum weight edge of all Adjacent A–B|4
edges of X = { A } edges of X = { A , B }
A–E|5
A–C|6
4
A 4
A
A–D|6
B–E|3
B X={A,B}
B B–C|2
X={A,B,C} C–E|6
2
C–D|1
C D–E|7

Step 3: Taking minimum weight edge of all Adjacent Step 4: Taking minimum weight edge of all Adjacent
edges of X = { A , B , C } edges of X = { A , B , C , D }

4
A 4
A

3
B B E
X = { A , B , C, D }
2 2

C 1 D C 1
D

X = { A , B , C, D, E }

All nodes of graph are there with set X, so we obtained minimum spanning tree of cost: 4 + 2 + 1 + 3 = 10
A 5
4
3
B E
Using Kruskal’s Algorithm
6
2 5 6 7

C D
1

Step 1: Taking min edge (C,D) Step 2: Taking next min edge (B,C) Step 3: Taking next min edge (B,E)

3
B B E

2 2
C 1
D
C 1 D C 1 D

Step 4: Taking next min edge (A,B) Step 5: Taking next min edge (A,E) it forms cycle so do not consider
Step 6: Taking next min edge (C,E) it forms cycle so do not consider
4
A Step 7: Taking next min edge (A,D) it forms cycle so do not consider
Step 8: Taking next min edge (A,C) it forms cycle so do not consider
3 Step 9: Taking next min edge (E,D) it forms cycle so do not consider
B E
All edges of graph has been visited,
2
so we obtained minimum spanning tree of cost:
C D 4 + 2 + 1 + 3 = 10
1
Give example and applications of directed and undirected graphs. Find the
adjacency matrix for the graph shown in Fig.

1 Adjacency matrix for the given graph


1 2 3 4 5 6
6 1 0 1 0 0 0 0
2 3 2 0 0 0 1 0 0
3 1 0 0 0 0 0
4 0 0 1 0 1 0
5 0 0 1 0 0 1
4 5 6 1 0 1 0 0 0

Applications of graph:
 Electronic Circuits
o Printed Circuit Board
o Integrated Circuit
 Transportation networks
o Highway networks
Modeling a road network with vertexes as towns and edge costs as distances.
o Water Supply networks
Modeling a water supply network. A cost might relate to current or a function of capacity and
length. As water flows in only 1 direction, from higher to lower pressure connections or
downhill, such a network is inherently an acyclic directed graph.
o Flight network
Minimizing the cost and time taken for air travel when direct flights don't exist between starting
ending
and
irports.
 Computer networks
o Local Area Network
o Internet
Dynamically modeling the status of a set of routes by which traffic might be directed over the
Internet.
o Web
Using a directed graph to map the links between pages within a website and to analyze ease of
navigation between different parts of the site.
Databases
o Entity Relationship Diagram

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy