Professional Documents
Culture Documents
DSA Combined
DSA Combined
Neetu Narayan
1
Introduction to Data Structures
ASET
OBJECTIVES
2
Definitions ASET
What is Data?
• Data is a collection of raw facts and figures.
• It is produced by many sources such as: recordings and
readings from a scientific experiment, generated by
some sensor or hardware, census..etc.
4
Types of Data Structures ASET
2) Complex or compound
A) Linear : sequential
e.g. arrays, stacks, queues, linked list etc.
B) Non-Linear : Non Sequential
e.g. trees, graphs etc.
5
Classification ASET
Linked list
queue
tree stack
ASET
Contiguous(Array) Vs Noncontiguous(List)
8
Memory representation ASET
9
ASET
10
Operations on Data Structures ASET
What is an algorithm?
12
Algorithm ASET
13
Complexity Theory ASET
14
Time-Space Tradeoff ASET
15
ASET
2) Average Case
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.
3) Best Case
In the best case analysis, we calculate lower bound on running
time of an algorithm.
16
ASET
Algorithm Notation:
• Before the steps, define the purpose of the algorithm.
• Number of steps in an algorithm should be finite.
• Use READ for input statement and PRINT OR WRITE for output
statement.
• Comments are enclosed within square brackets. [ ]
• Use EXIT or STOP to show end of an algorithm
• For Selection logic, use
Single alternative
If condition, then:
[Module A]
[End of Structure]
17
ASET
Algorithm Notation:
Double Alternative Multiple Alternative
If condition, then: If condition(1), Then:
[Module B] [Module A]
Else: Else If condition(2), Then:
[Module A] [Module B]
[End of If structure] .
.
Else If condition(N), Then:
[Module N]
Else:
[Module M]
[End of If structure]
18
ASET
19
ASET
Linear Arrays
A linear array is a list of finite number n of homogeneous
data elements such that:
a) The elements are referenced by an index set consisting
of n consecutive numbers.
b) The elements are stored in consecutive memory
locations.
Examples:
1. Let A be a linear array with LB=25 and UB=74. Find the
length of an array.
21
ASET
It is denoted by Base(arr).
Address of kth element of an array arr is given by:
Address(arr[k]) or LOC(arr[k]) = base(arr)+w(k-LB)
Where w is the number of words per memory cell.
22
ASET
23
ASET
24
ASET
Step 1:
Step 2:
Step 3:
Step 1:
Find element to delete
Step 2:
Shift elements to the left to fill
the gap
Step 3:
Decrease No. of elements in
array by 1
27
ASET
28
ASET
29
ASET
Example:
Let A be a sorted array with 12 elements.
10,15, 22, 34, 45, 58,69, 70,77,89,95, 112
Use binary search algorithm to find element
10 in the list
31
ASET
Examples:
Q1. Let A be an array of size 100x50 is given. Find the address of the
element A[52,13] f the array is stored using
a) Row-Major order
b) Column-Major order
where w=2.
35
ASET
Multidimensional Arrays:
36
ASET
37
References ASET
• https://www.building-blocks.com/content/blogs/different-types-of-data-sources
• https://www.atnyla.com/tutorial/data-structure-introduction/3/299
• https://www.programmingsimplified.com/c/source-code/c-program-linear-search
• https://www.geeksforgeeks.org/introduction-to-algorithms/
38
ASET
39
Amity School of Engineering and Technology
Contents :
Stack
Definition
Stack Representation
Array Representation
Linked List Representation
Operations on Stacks- Push & Pop
2
Amity School of Engineering and Technology
Learning Objectives
• Impart in-depth knowledge of data structure and its implementation
in computer programs.
• Make students understand the concepts of Stack linear data structure.
• Make students understand the applications of Stack.
3
Amity School of Engineering and Technology
Recommended Reading
Textbooks:
• Yashwant Kanetkar,”Data Structure using C”, BPB Publication, 5th Edition ,2011
• A.Tannenbaum,Y. Lanhgsam and A.J. Augenstein ,” Data Structures Using C And C++ “,Prentice Hall of
India,2nd Edition,2009.
• Jean-Paul Tremblay, P.G Sorenson, “An Introduction to Data Structures with applications”, Mcgraw-Hill
,2nd Edition ,1984.
Reference Book:
• Robert L Kruse, “Data Structure and Program Design in C”, Prentice Hall (1991).
• Noel Kalicharan ,“Data Structure in C” ,Ist Edition Create space publisher, 2008.
• Mark Allen Weiss,“Data Structure and algorithm Analysis in C”,2nd Edition AddisonWesley,1996.
• E. Balagurusamy, “Problem Solving through C language”, TMH publication, Fourth Edition, 2008.
• R.S Salaria ,“Data Structures & Algorithms using C”,Khanna Publication,4th Edition,2009
• E.Horowitz and S.Sahni,”Fundamentals of Data Structures in C “,2nd Edition, Universities Press,2008.
4
Amity School of Engineering and Technology
Module Assessment
• Quiz (Conceptual and Numerical Based)
• Assignment
5
Amity School of Engineering and Technology
STACK
Definition: Stack is a linear data
structure that principally works on
the Last-in First-out (LIFO). The
element that is inserted first will be
out at last and vice-versa
Examples of Stack
6
Amity School of Engineering and Technology
STACK TERMINOLOGIES
1. Top of Stack: TOP is the pointer
that shows the position of the
topmost element of the stack.
2. MaxStack: MaxStack shows the
maximum size of the stack.
(“How many elements?”)
3. Stack Operations:
PUSH()
POP()
7
Amity School of Engineering and Technology
8
Amity School of Engineering and Technology
ARRAY REPRESENTATION
9
Amity School of Engineering and Technology
10
Amity School of Engineering and Technology
STACK OPERATIONS
There are two operations of stack:
1) PUSH Operation
2) POP Operation
11
Amity School of Engineering and Technology
12
Amity School of Engineering and Technology
Goto Step 4
[End of if structure]
Step 4: EXIT
13
Amity School of Engineering and Technology
50 TOP
TOP
40 40
TOP
30 30 30
TOP
20 20 20 20
TOP
10 10 10 10 10
Time Complexity
Push() O(1)
Pop() O(1)
Display() O(n)
16
Expression
An expression is a collection of operators and operands that represents a specific value.
Based on the operator position, expressions are divided into three categories. They are
as follows...
• Infix Expression
• Postfix Expression (Reverse Polish)
• Prefix Expression (Polish)
17
Types of Expression
Infix Expression
• Operator is used in between operands.
Operand1 Operator Operand2
• Example : a+b
Postfix Expression
• Operator is used after operands.
Operand1 Operand2 Operator
• Example : ab+
Prefix Expression
• operator is used in between operands.
Operator Operand1 Operand2
• Example : +ab
18
INFIX TO POSTFIX ALGORITHM
Let Q be an expression written in infix notation. This algorithm converts the infix expression into Postfix expression P.
Read all the symbols one by one from left to right in the given Infix Expression.
1. Push "(" onto STACK, and add ")" to the end of Q
2. Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the stack is empty
3. If an operand is encountered add it to P
4. If a left parenthesis is encountered push it onto the stack
5. if an operator is encountered , then
(a) Repeatedly pop from STACK and add to P each operator (on top of the STACK) which has same precedence as or higher precedence than
the operator encountered
(b) Add the encountered operator to the stack
[end of IF structure]
6. if a right parenthesis is encountered, then:
(a) repeatedly pop from the stack and add to P each operator (on top of the STACK) until a left parenthesis is encountered
(b) remove the left parenthesis [do not add left parenthesis to P]
[End of IF structure]
[End of step 2 loop]
19
Infix to Postfix
Infix Expression= A*B+C
20
Quiz 2
1. A-(B*C/D^F) +G *H/I-J
2. (A-2*(B+C)/D*E)+F
3. A+B*C/D-F+A^E
21
Evaluation of Postfix
Read all the symbols one by one from left to right in the given Postfix Expression.
22
Example: A B * C +
23
Example: Evaluate (5+6*3)+(5+6 )*3 using Postfix Notation
Infix expression: (5+6*3)+(5+6 )*3)
Current Symbol Stack Postfix Expression Priority Level
1. +, -
( (( 2. *, /
3. ^
5 (( 5 4. ++, --
+ ((+ 5
6 ((+ 56
* ((+* 56
3 ((+* 563
) ( 563*+
+ (+ 563*+
( (+( 563*+
5 (+( 563*+5
+ (+(+ 563*+5 24
Infix expression: (5+6*3)+((5+6 )*3 = 56 )
25
Postfix Evaluation of Expression: 5 6 3 * + 5 6 + 3 * +
Reading Symbol Stack operation Stack Content
5 Push 5
6 Push 56
3 Push 563
* Pop3,Pop 6 and push 6*3 5 18
+ Pop18,Pop 5 and Push 5+18 23
5 Push 23 5
6 Push 23 5 6
+ Pop6,Pop 5 and push 5+6 23 11
3 Push 23 11 3
* Pop3,Pop 11 and Push 11*3 23 33
+ Pop33, Pop 23 and Push 23+33 56
26
Practice Question
Evaluate the following expression using postfix notation.
1) 5*2+(16/2^3-3*2)+14/7
2) 120-7^3/49+(5*2-2^3)-40
27
Infix To Prefix Algorithm
Read all the symbols one by one from right to left in the given Infix Expression.
1.Push ‘)‘ onto Stack and ‘(’ at the end of the infix expression.
2.If the symbol is an operand, then directly add it to output expression.
3.If the reading symbol is right parenthesis ‘)', then Push it on to the Stack.
4.If the reading symbol is left parenthesis ‘(', then pop all the symbols from the stack until a
right parenthesis appears. Discard the right parenthesis and add remaining popped symbols to
the output expression in the order in which they are popped.
5.If the reading symbol is an operator (+ , - , * , / etc.,), then Check, if the operator on the top of
the stack has higher precedence than the one being read, pop the operator and add it to the
output expression. Repeat the process until a lower or equal precedence operator appears at
the top of the stack. Then push the current operator onto the stack.
6.At the end after reading the entire infix expression, reverse the output expression.
Reverse of output expression is the Prefix expression.
28
Quiz 1
1. A-(B*C/D^F) +G *H/I-J
2. (A-2*(B+C)/D*E)+F
3. A+B*C/D-F+A^E
29
EXAMPLE: A*B+C
30
Evaluation of Prefix:
Read all the symbols one by one from right to left in the given Prefix Expression.
• If the reading symbol is operator (+ , - , * , / etc.,), then perform two pop operations
and store the two popped operands in two different variables (operand1( stack top
symbol) and operand2( next-to-top symbol)). Then perform reading symbol operation
using operand1 operator operand2 and push result back on to the Stack.
31
Example: +*ABC
Reading Symbol Stack operation Stack Content
C Push C
B Push CB
A Push CBA
32
Example: Evaluate (5+6*3)+(5+6 )*3 using Prefix Notation
Infix expression: ( (5+6*3)+(5+6 )*3
Current Symbol Stack Output Expression
3 ) 3
* )* 3
) )*) 3
6 )*) 36
+ )*)+ 36
5 )*)+ 365
( )* 365+
+ )+ 365+*
) )+) 365+*
3 )+) 365+*3
* )+)* 365+*3 33
Infix expression: ( (5+6*3)+(5+6 )*3
Current Symbol Stack Output Expression
6 )+)* 365+*36
+ )+)+ 365+*36*
5 )+)+ 365+*36*5
( )+ 365+*36*5+
( 365+*36*5++
34
Prefix Evaluation of Expression: + + 5 * 6 3 * + 5 6 3
36
Amity School of Engineering and Technology
Parenthesis Checker
Algorithm:
1. Whenever an opening parenthesis is encountered, push it on stack.
2. For closing parenthesis, check what is at the top of the stack, if it corresponding opening parenthesis,
remove it from the top of the stack.
3. If parenthesis at the top of the stack is not corresponding opening parenthesis, return false, as there is
no point check the string further.
4. After processing entire string, check if stack is empty or not.
4.a If the stack is empty, return true.
4.b If stack is not empty, parenthesis do not match
37
Amity School of Engineering and Technology
Example:{()[(([])[])]}
Input Operation Stack Symbol
{()[([])]} PUSH {
()[([])]} PUSH {(
)[([])]} POP {
[([])]} PUSH {[
([])]} PUSH {[(
[])]} PUSH {[([
])]} POP {[(
)]} POP {[
]} POP {
} POP Empty
Accepted
38
Amity School of Engineering and Technology
Example:{()(}
Input Input Operation Stack Symbol
{()(} { PUSH {
()(} ( PUSH {(
)(} ) POP {
(} ( PUSH {(
} } POP {(
Recursion
Recursion is the process by which function calls
itself repeatedly, until the specified condition has
been satisfied.
To solve a problem recursively, two conditions
must be satisfied:
1. A base value should be defined for which the
function should not call itself.
2. At each function call, the argument of the
function should move close to the base
value.
40
Amity School of Engineering and Technology
41
Amity School of Engineering and Technology
Towers of Hanoi
• Mathematical puzzle
• Consists of three tower (pegs) and more than one rings;
• These rings are of different sizes and stacked upon in ascending order
• There are other variations of puzzle where the number of disks increase, but the
tower count remains the same.
42
Amity School of Engineering and Technology
Rules
The mission is to move all the disks to some another tower without
violating the sequence of arrangement.
1.Only one disk can be moved among the towers at any given time.
43
Amity School of Engineering and Technology
Initial A->C
A->B C->B
45
Amity School of Engineering and Technology
A->C B->A
B->C A->C
46
Amity School of Engineering and Technology
47
ASET
Neetu Narayan
1
Introduction to Data Structures
ASET
OBJECTIVES
• To understand basic definitions and
representation of linear arrays in memory.
• To understand and implement operations on
array data structure.
• To understand and implement two-dimensional
arrays and their memory representation.
• To understand the use of multi-dimensional
arrays and implement them.
2
ASET
Examples:
Q1. Let A be an array of size 100x50 is given. Find the address of the
element A[52,13] f the array is stored using
a) Row-Major order
b) Column-Major order
where w=2.
6
ASET
Multidimensional Arrays:
7
ASET
8
ASET
Example:
9
Sparse Matrix ASET
10
ASET
11
Character String in C ASET
Declaration of Strings
char str_name[size];
12
In built String Functions ASET
1 strcpy(s1, s2);
Copies string s2 into string s1.
2 strcat(s1, s2);
Concatenates string s2 onto the end of string s1.
3 strlen(s1);
Returns the length of string s1.
4 strcmp(s1, s2);
Returns 0 if s1 and s2 are the same; less than 0 if s1<s2; greater than 0 if
s1>s2.
13
Quiz 1
Write an algorithm to find multiplication
of two matrices
Quiz 1
Matrix Multiplication Algorithm
Let A be a matrix of size MxN and B be a matrix of size NxP. This algorithm
finds multiplication of the matrices
Step1: Repeat for I=1 to M
Step2: Repeat for J=1 to P
Step3: mult[I][J]=0
Step4: Repeat for S=1 to N
Step5: mult[I][J]=mult [I][J] +A[I][S]*B[S][J]
[end of step4 loop]
[end of step 2 loop]
[end of step1 loop]
Step6: EXIT
References ASET
• https://www.building-blocks.com/content/blogs/different-types-of-data-sources
• https://www.atnyla.com/tutorial/data-structure-introduction/3/299
• https://www.programmingsimplified.com/c/source-code/c-program-linear-search
• https://www.geeksforgeeks.org/introduction-to-algorithms/
16
ASET
17
Amity School of Engineering and Technology
Contents :
Stack
qDefinition
qStack Representation
qArray Representation
qLinked List Representation
q Operations on Stacks- Push & Pop
2
Amity School of Engineering and Technology
Learning Objectives
• Impart in-depth knowledge of data structure and its implementation
in computer programs.
• Make students understand the concepts of Stack linear data
structure.
• Make students understand the applications of Stack.
3
Amity School of Engineering and Technology
Recommended Reading
Textbooks:
• Yashwant Kanetkar,”Data Structure using C”, BPB Publication, 5th Edition ,2011
• A.Tannenbaum,Y. Lanhgsam and A.J. Augenstein ,” Data Structures Using C And C++ “,Prentice Hall of
India,2nd Edition,2009.
• Jean-Paul Tremblay, P.G Sorenson, “An Introduction to Data Structures with applications”, Mcgraw-Hill ,2nd
Edition ,1984.
Reference Book:
• Robert L Kruse, “Data Structure and Program Design in C”, Prentice Hall (1991).
• Noel Kalicharan ,“Data Structure in C” ,Ist Edition Create space publisher, 2008.
• Mark Allen Weiss,“Data Structure and algorithm Analysis in C”,2 nd Edition
AddisonWesley,1996.
• E. Balagurusamy, “Problem Solving through C language”, TMH publication, Fourth Edition,
2008.
• R.S Salaria ,“Data Structures & Algorithms using C”,Khanna Publication,4 th Edition,2009
• E.Horowitz and S.Sahni,”Fundamentals of Data Structures in C “,2 nd Edition, Universities
Press,2008. 4
Amity School of Engineering and Technology
Module Assessment
• Quiz (Conceptual and Numerical Based)
• Assignment
5
Amity School of Engineering and Technology
STACK
Definition: Stack is a linear data
structure that principally works on
the Last-in First-out (LIFO). The
element that is inserted first will
be out at last and vice-versa
Examples of Stack
6
Amity School of Engineering and Technology
STACK TERMINOLOGIES
1. Top of Stack: TOP is the pointer
that shows the position of the
topmost element of the stack.
2. MaxStack: MaxStack shows the
maximum size of the stack.
(“How many elements?”)
3. Stack Operations:
Ø PUSH()
Ø POP()
7
Amity School of Engineering and Technology
8
Amity School of Engineering and Technology
ARRAY REPRESENTATION
9
Amity School of Engineering and Technology
10
Amity School of Engineering and Technology
STACK OPERATIONS
There are two operations of stack:
1) PUSH Operation
2) POP Operation
11
Amity School of Engineering and Technology
12
Amity School of Engineering and Technology
Goto Step 4
[End of if structure]
Step 4: EXIT
13
Amity School of Engineering and Technology
Time Complexity
Push() O(1)
Pop() O(1)
Display() O(n)
16
Expression
An expression is a collection of operators and operands that represents a
specific value.
Based on the operator position, expressions are divided into three categories.
They are as follows...
• Infix Expression
• Postfix Expression (Reverse Polish)
• Prefix Expression (Polish)
17
Types of Expression
Infix Expression
• Operator is used in between operands.
Operand1 Operator Operand2
• Example : a+b
Postfix Expression
• Operator is used after operands.
Operand1 Operand2 Operator
• Example : ab+
Prefix Expression
• operator is used in between operands.
Operator Operand1 Operand2
• Example : +ab
18
INFIX TO POSTFIX ALGORITHM
Let Q be an expression written in infix notation. This algorithm converts the infix expression into Postfix expression P.
Read all the symbols one by one from left to right in the given Infix Expression.
1. Push "(" onto STACK, and add ")" to the end of Q
2. Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the stack is empty
3. If an operand is encountered add it to P
4. If a left parenthesis is encountered push it onto the stack
5. if an operator is encountered , then
(a) Repeatedly pop from STACK and add to P each operator (on top of the STACK) which has same precedence as or higher
precedence than the operator encountered
(b) Add the encountered operator to the stack
[end of IF structure]
6. if a right parenthesis is encountered, then:
(a) repeatedly pop from the stack and add to P each operator (on top of the STACK) until a left parenthesis is encountered
(b) remove the left parenthesis [do not add left parenthesis to P]
[End of IF structure]
[End of step 2 loop]
19
Infix to Postfix
Infix Expression= A*B+C
20
Quiz 2
1. A-(B*C/D^F) +G *H/I-J
2. (A-2*(B+C)/D*E)+F
3. A+B*C/D-F+A^E
21
Evaluation of Postfix
Read all the symbols one by one from left to right in the given Postfix
Expression.
23
Example: Evaluate (5+6*3)+(5+6 )*3 using Postfix Notation
Infix expression: (5+6*3)+(5+6 )*3)
Priority
Current Symbol Stack Postfix Expression Level
1. +, -
( (( 2. *, /
5 (( 5 3. ^
4. ++, --
+ ((+ 5
6 ((+ 56
* ((+* 56
3 ((+* 563
) ( 563*+
+ (+ 563*+
( (+( 563*+
5 (+( 563*+5
+ (+(+ 563*+5 24
Infix expression: (5+6*3)+((5+6 )*3 = 56 )
25
Postfix Evaluation of Expression: 5 6 3 * + 5 6 + 3 *
+
Reading Symbol Stack operation Stack Content
5 Push 5
6 Push 56
3 Push 563
* Pop3,Pop 6 and push 6*3 5 18
+ Pop18,Pop 5 and Push 5+18 23
5 Push 23 5
6 Push 23 5 6
+ Pop6,Pop 5 and push 5+6 23 11
3 Push 23 11 3
* Pop3,Pop 11 and Push 11*3 23 33
+ Pop33, Pop 23 and Push 23+33 56
26
Practice Question
Evaluate the following expression using postfix notation.
1) 5*2+(16/2^3-3*2)+14/7
2) 120-7^3/49+(5*2-2^3)-40
27
Infix To Prefix Algorithm
Read all the symbols one by one from right to left in the given Infix Expression.
1.Push ‘)‘ onto Stack and ‘(’ at the end of the infix expression.
2.If the symbol is an operand, then directly add it to output expression.
3.If the reading symbol is right parenthesis ‘)', then Push it on to the Stack.
4.If the reading symbol is left parenthesis ‘(', then pop all the symbols from the stack
until a right parenthesis appears. Discard the right parenthesis and add remaining
popped symbols to the output expression in the order in which they are popped.
5.If the reading symbol is an operator (+ , - , * , / etc.,), then Check, if the operator on
the top of the stack has higher precedence than the one being read, pop the
operator and add it to the output expression. Repeat the process until a lower or
equal precedence operator appears at the top of the stack. Then push the current
operator onto the stack.
6.At the end after reading the entire infix expression, reverse the output expression.
Reverse of output expression is the Prefix expression.
28
Quiz 1
1. A-(B*C/D^F) +G *H/I-J
2. (A-2*(B+C)/D*E)+F
3. A+B*C/D-F+A^E
29
EXAMPLE: A*B+C
30
Evaluation of Prefix:
Read all the symbols one by one from right to left in the given Prefix
Expression.
B Push CB
A Push CBA
32
Example: Evaluate (5+6*3)+(5+6 )*3 using Prefix Notation
Infix expression: ( (5+6*3)+(5+6 )*3
Current Symbol Stack Output Expression
3 ) 3
* )* 3
) )*) 3
6 )*) 36
+ )*)+ 36
5 )*)+ 365
( )* 365+
+ )+ 365+*
) )+) 365+*
3 )+) 365+*3
* )+)* 365+*3 33
Infix expression: ( (5+6*3)+(5+6 )*3
Current Symbol Stack Output Expression
6 )+)* 365+*36
+ )+)+ 365+*36*
5 )+)+ 365+*36*5
( )+ 365+*36*5+
( 365+*36*5++
34
Prefix Evaluation of Expression: + + 5 * 6 3 * + 5 6
3
Reading Symbol Stack operation Stack Content
3 Push 3
6 Push 36
5 Push 365
+ Pop 5, Pop 6, Push(5+6) 3 11
* Pop11, Pop3, Push(11*3) 33
3 Push 33 3
6 Push 33 3 6
* Pop 6, Pop3, Push(6*3) 33 18
5 Push 33 18 5
+ Pop 5, Pop 18, Push(5+18) 33 23
+ Pop 23, Pop33, Push(33+23) 56
35
Practice Question
Evaluate the following expression using postfix notation.
1) 5*2+(16/2^3-3*2)+14/7
2) 120-7^3/49+(5*2-2^3)-40
36
Amity School of Engineering and Technology
Parenthesis Checker
Algorithm:
1. Whenever an opening parenthesis is encountered, push it on stack.
2. For closing parenthesis, check what is at the top of the stack, if it corresponding opening
parenthesis, remove it from the top of the stack.
3. If parenthesis at the top of the stack is not corresponding opening parenthesis, return false,
as there is no point check the string further.
4. After processing entire string, check if stack is empty or not.
4.a If the stack is empty, return true.
4.b If stack is not empty, parenthesis do not match
37
Amity School of Engineering and Technology
Example:{()[(([])[])]}
Input Operation Stack Symbol
{()[([])]} PUSH {
()[([])]} PUSH {(
)[([])]} POP {
[([])]} PUSH {[
([])]} PUSH {[(
[])]} PUSH {[([
])]} POP {[(
)]} POP {[
]} POP {
} POP Empty
Accepted
38
Amity School of Engineering and Technology
Example:{()(}
Input Input Operation Stack Symbol
{()(} { PUSH {
()(} ( PUSH {(
)(} ) POP {
(} ( PUSH {(
} } POP {(
Recursion
Recursion is the process by which function
calls itself repeatedly, until the specified
condition has been satisfied.
To solve a problem recursively, two
conditions must be satisfied:
1. A base value should be defined for
which the function should not call
itself.
2. At each function call, the argument of
the function should move close to the
base value.
40
Amity School of Engineering and Technology
41
Amity School of Engineering and Technology
Towers of Hanoi
• Mathematical puzzle
• Consists of three tower (pegs) and more than one rings;
• These rings are of different sizes and stacked upon in ascending order
• There are other variations of puzzle where the number of disks increase,
but the tower count remains the same.
42
Amity School of Engineering and Technology
Rules
The mission is to move all the disks to some another tower
without violating the sequence of arrangement.
1.Only one disk can be moved among the towers at any given
time.
43
Amity School of Engineering and Technology
Initial A->C
A->B C->B
45
Amity School of Engineering and Technology
A->C B->A
B->C A->C
46
Amity School of Engineering and Technology
47
Data structures using C
Module 2
STACKS AND QUEUES
Prepared By
Ms. Neetu Narayan
48
QUEUE:
QUEUE: Array implementation, Linked List implementation, Circular Queue,
Applications of queue: Priority queue, Double ended queue
49
• Queue is a linear data structure in which the insertion and deletion
operations are performed at two different ends.
• In a queue data structure, the insertion operation is performed at a
position which is known as 'rear' and the deletion operation is
performed at a position which is known as 'front'.
• Queue follows FIFO (First In First Out) principle.
• In a queue data structure, the insertion operation is performed using
a function called "enQueue()" and deletion operation is performed
using a function called "deQueue()".
Operations on Queue
•enQueue(value) - (To insert an element into the
queue)
•deQueue() - (To delete an element from the
queue)
•display() - (To display the elements of the queue)
Implementation of Queue
ØUsing Array
ØUsing Linked List
Queue using Array
• Step 1: Create a one dimensional array with above defined SIZE
(int queue[SIZE])
• Step 2: Define two integer variables 'front' and 'rear' and initialize
both with '-1'. (int front = -1, rear = -1)
#define SIZE 5
int queue[SIZE],
Int front=-1,rear=-1;
EnQueue(value) - Inserting value
Step 1: Check whether queue is FULL. (rear == SIZE-1)
Step 2: If it is FULL, then display "Queue is FULL!!! and terminate
Step 3: If it is EMPTY, then place the first item in position front =
rear = 0
Step 4 : if NOT FULL,NOT EMPTY , then increment rear value by
void enqueue(value)
{ one (rear++) and set queue[rear] = value.
if(rear == SIZE-1)
printf("Queue is Full“);
else if(front == -1 && rear ==-1)
{ front = 0;
rear = 0;
queue[rear] = value;
}
else
{ rear++;
queue[rear] = value;
}
}
Example of Insertion in Queue
dequeue() – Removing value
Step 1: Check whether queue is EMPTY. (front == rear=-1)
Step 2: If it is EMPTY, then display "Queue is EMPTY!!" and terminate.
Step 3: If it is NOT EMPTY, then check if both front and rear are
equal (front == rear), then set both front and rear to '-1'
(front = rear = -1).
else increment the front value by one (front ++). Then
display queue[front] as deleted element.
Void dequeue()
{ if(front == rear)
printf(“Queue is Empty!!! “);
else {
printf(“Deleted : %d “, queue[front]);
if(front == rear)
front = rear = -1;
else
front++;
}
}
Example of Deletion in Queue
display() - Displays the elements of a Queue
1: Check whether queue is EMPTY. (front == rear)
2a: If it is EMPTY, then display "Queue is EMPTY!!!" and terminate.
2b: If it is NOT EMPTY, then define an integer variable 'i' and set
'i = front+1'
3: Display 'queue[i]' value and increment 'i' value by one (i++). Repeat
the same until 'i' value is equal to rear (i <= rear)
void display()
{
if(front ==-1 && rear= = -1)
printf(“Queue is Empty!!! “);
else
{ int i;
printf(“Queue elements are:");
for(i=front; i<=rear; i++)
printf(“%d”, queue[i]);
}
}
Linked List implementation
63
e.g.
64
e.g.
65
e.g.
66
Deletion in Circular Queue
Step 1: If FRONT = -1 then dequeue ()
Write ("Circular Queue Underflow“) {
GOTO Step 4 Step 2: if(isempty())
SET Step 2: SET return
VAL=QUEUE[FRONT] else if(front = rear) // Single element in
Step 3: If FRONT = REAR then Queue
SET FRONT=REAR=-1 { front=-1;
ELSE rear=-1;
IF FRONT=MAX-1 }
SET FRONT=0 Else
ELSE {
SET FRONT=FRONT+1 Front = (front +1)%SIZE
[END OF IF] }
[END OF IF] }
Step 4: EXIT
e.g.
68
e.g.
69
e.g.
70
QUEUE: Array implementation, Linked List implementation,
Circular Queue, Applications of queue: Priority queue,
Double ended queue
Priority Queue
• In priority queue, each element is assigned a priority.
• Priority of an element determines the order in which the
elements will be processed.
• Rules:
1. An element with higher priority will processed before an
element with a lower priority.
2. Two elements with the same priority are processed on a
First Come First Serve basis.
Types of Priority Queue
1. Ascending Priority Queue
• In this type of priority queue, elements can be inserted into any
order but only the smallest element can be removed.
Front Rear
20 15 10
A[0] A[1] A[2] A[3] A[4]
Front Rear
2 1 1 1
5
A[0] 5
A[1] 3
A[2] 0
A[3] A[4]
Front Rear
Array Representation of Priority Queue
Deletion Operation:
• While deletion, the element at the front is always
deleted.
Array Representation of Priority
Queue 20 15 13 10
A[0] A[1] A[2] A[3] A[4]
Front Rear
15 13 10
A[0] A[1] A[2] A[3] A[4]
Front Rear
13 10
A[0] A[1] A[2] A[3] A[4]
Front Rear
Double ended Queue (Deque)
Double Ended Queue is also a Queue data structure in which the
insertion and deletion operations are performed at both the ends
(front and rear).
Dept. of CSE
B.Tech, 3th Sem
Ms. Neetu Narayan
82
Agenda…. ASET
83
Linked list ASET
implementation of
• Instead of using array, we can also use linked list to implement stack.
•
stack
Linked list allocates the memory dynamically.
• In linked list implementation of stack, the nodes are maintained non-contiguously in the
memory.
• Each node contains a pointer to its immediate successor node in the stack.
• Stack is said to be overflown if the space left in the memory heap is not enough to
create a node.
• The top most node in the stack always contains null in its address field.
84
ASET
85
Adding a node to the stack (Push ASET
operation)
• Adding a node to the stack is referred to as push operation.
• Time Complexity : O(1)
• In order to push an element onto the stack, the following steps are
involved.
1. Create a node first and allocate memory to it.
2. If the list is empty then the item is to be pushed as the start node of the list.
This includes assigning value to the data part of the node and assign null to the address
part of the node.
3. If there are some nodes in the list already, then we have to add the new element in the
beginning of the list.
For this purpose, assign the address of the starting element to the address field of the
new node and make the new node, the starting node of the list.
86
ASET
87
push(value) - Inserting an element into the Stack ASET
void push ()
{ else //some nodes are already
int val; present in the stack
struct node *ptr =(struct node*)malloc(sizeof(str {
uct node)); ptr->val = val;
if(ptr == NULL) ptr->next = head;
{ head=ptr;
printf("not able to push the element");
} }
else printf("Item pushed");
{
printf("Enter the value"); }
scanf("%d",&val); }
if(head==NULL) //No node is present in
the stack
{
ptr->val = val;
ptr -> next = NULL;
head=ptr;
}
88
Deleting a node from the stack (POP ASET
operation)
• Deleting a node from the top of stack is referred to as pop operation.
• Deleting a node from the linked list implementation of stack is different from
that in the array implementation.
• In order to pop an element from the stack, we need to follow the following
steps :
• Check for the underflow condition: The underflow condition occurs when
we try to pop from an already empty stack.
The stack will be empty if the head pointer of the list points to null.
• Adjust the head pointer accordingly: In stack, the elements are popped
only from one end, therefore, the value stored in the head pointer must be
deleted and the node must be freed.
The next node of the head node now becomes the head node.
• Time Complexity : o(1)
89
pop() - Deleting an Element from a Stack
ASET
90
ASET
void pop()
{
int item;
struct node *ptr;
if (head == NULL)
{
printf("Underflow");
}
else
{
item = head->val;
ptr = head;
head = head->next;
free(ptr);
printf("Item popped");
}
}
91
Display the nodes (Traversing) ASET
Displaying all the nodes of a stack needs traversing all the nodes of the linked
list organized in the form of stack
1. Copy the head pointer into a temporary pointer.
2. Move the temporary pointer through all the nodes of the list and print
the value field attached to every node.
Time Complexity : o(n)
void display() else
{ {
int i; printf("Printing Stack elements \n");
struct node *ptr; while(ptr!=NULL)
ptr=head; {
if(ptr == NULL) printf("%d\n",ptr->val);
{ ptr = ptr->next;
printf("Stack is empty\n"); }
} }
}
92
ASET
93
Linked List implementation of
ASET
Queue
Drawback of array implementation
• Memory wastage : The space of the array, which is used to store queue elements,
can never be reused to store the elements of that queue because the elements can
only be inserted at front end and the value of front might be so high so that, all the
space before that, can never be filled.
94
Linked List
ASET
implementation of Queue
• The storage requirement of linked representation of a queue with n
elements is o(n) while the time requirement for operations is o(1).
• In a linked queue, each node of the queue consists of two parts i.e.
data part and the link part.
• Each element of the queue points to its immediate next element in the
memory.
• In the linked queue, there are two pointers maintained in the memory
i.e. front pointer and rear pointer.
• The front pointer contains the address of the starting element of the
queue while the rear pointer contains the address of the last element
of the queue.
• Insertion and deletions are performed at rear and front end
respectively.
• If front and rear both are NULL, it indicates that the queue is empty.
95
Operation on Linked Queue ASET
Insert operation
The insert operation append the queue by adding an element to the end of the
queue. The new element will be the last element of the queue.
Step 1: allocate the memory for the new node ptr by using the following statement.
96
ASET
There can be the two scenario of inserting this new node ptr into the linked queue.
In the first scenario, we insert element into an empty queue. In this case, the
condition front = NULL becomes true.
Now, the new element will be added as the only element of the queue and the next
pointer of front and rear pointer both, will point to NULL
97
ASET
In the second case, the queue contains more than one element.
The condition front = NULL becomes false.
In this scenario, we need to update the end pointer rear so that the next pointer of
rear will point to the new node ptr.
Since, this is a linked queue, hence we also need to make the rear pointer point to
the newly added node ptr. We also need to make the next pointer of rear point to
NULL.
98
ASET
Algorithm
99
ASET
Deletion
Deletion operation removes the element that is first inserted among all the queue elements.
Firstly, we need to check either the list is empty or not.
The condition front == NULL becomes true if the list is empty, in this case , we simply write
underflow on the console and make exit.
Otherwise, we will delete the element that is pointed by the pointer front.
For this purpose, copy the node pointed by the front pointer into the pointer ptr. Now, shift the
front pointer, point to its next node and free the node pointed by the node ptr.
ptr = front;
front = front -> next;
free(ptr);
100
ASET
Algorithm (delete)
101
ASET
1
ASET
Module-IV
Trees
Syllabus ASET
8
ASET
Module-IV
Trees
Syllabus ASET
4
Student Learning Outcomes: ASET
6
Tree ASET
7
Basic terminology
• Root Node :-
The topmost node in the tree hierarchy.
The root node is the one which doesn't have any
parent.
• Sub Tree :-
If the root node is not null, the tree T1, T2 and
T3 is called sub-trees of the root node.
• Leaf Node :-
The node of tree, which doesn't have any child
node, is called leaf node.
It is the bottom most node of the tree.
There can be any number of leaf nodes present
in a general tree.
Also called external nodes.
• Path :-
The sequence of consecutive edges is called
path.
In the tree shown in the above image, path to
the node E is A→ B → E.
Basic terminology
• Ancestor node :-
An ancestor of a node is any predecessor
node on a path from root to that node.
The root node doesn't have any ancestors.
In the tree shown, the node F have the
ancestors, B and A.
• Degree :-
Degree of a node is equal to number of
children, a node have.
In the tree shown in the above image, the
degree of node B is 2.
Degree of a leaf node is always 0 while in a
complete binary tree, degree of each node
is equal to 2.
• Level Number :-
Each node of the tree is assigned a level
number in such a way that each node is
present at one level higher than its parent.
Root node of the tree is always present at
level 0.
Types of Trees ASET
General
tree
Tournament
Forest
Tree
Trees
Expression
Binary Tree
Tree
Binary
search Tree
10
General Tree ASET
• All the nodes except the root node are present at number
of levels.
• The nodes which are present on the same level are called
siblings while the nodes which are present on the different
levels exhibit the parent-child relationship among them.
• Obtained by deleting the root node and the edges which connects
root node to the first level node.
12
Binary Tree ASET
• The node present at the top-most level is called the root node.
13
Binary Search Tree ASET
• All the elements in the left sub-tree are less than the root while
elements present in the right sub-tree are greater than or equal
to the root node element.
14
Expression Tree ASET
15
Tournament Tree ASET
16
Summary ASET
Thank You..☺
21
ASET
Module-IV
Trees
Syllabus ASET
4
Student Learning Outcomes: ASET
• Binary Tree is a special type of generic tree in which, each node can have
at most two children.
6
Types of Binary Tree ASET
7
Types of Binary Tree ASET
– A complete binary tree is a binary tree that contains 2^l nodes at each
level between level 0 and h-1. (where l=level)
8
Types of Binary Tree ASET
9
Types of Binary Tree ASET
10
Types of Binary Tree ASET
Skewed Tree
– A skewed binary tree is a type of binary tree in which all the nodes have only
either one child or no child.
– 1. Left Skewed Binary Tree:
• These are those skewed binary trees in which all the nodes are having a left
child or no child at all.
• It is a left side dominated tree. All the right children remain as null.
– 2. Right Skewed Binary Tree:
• These are those skewed binary trees in which all the nodes are having a right
child or no child at all.
• It is a right side dominated tree. All the left children remain as null.
11
Types of Binary Tree ASET
13
Some Interesting ASET
14
Some Interesting ASET
15
Some Interesting ASET
A
level p
A n=6
level p Tree T’ I= 0+1+1+2+2+2= 8
E= 2+3+3+3+3+3+3=20
Internal Nodes: k-1 ------(1)
Tree T
Internal Path length I’=I-p
External Path Length:
Internal node: k
E’= E-2(p+1)+p
External Node length: E
E’=I’+2(k-1) [we assume that
Internal Node length: I
(1)is true]
E-2(p+1)+p= I-p +2(k-1)
E=I+2k 16
Binary Tree representation ASET
Sequential Representation
– This is the simplest memory allocation technique to store the
tree elements
17
ASET
Note:
1. The root node of the tree
will be present at the
1st index of the array.
2. If a node is indexed k, it will
be stored in kth place in the
array
18
ASET
19
ASET
Note:
1. Root is stored at
index 1
2. For any node k, left
child is stored at 2k,
right child at 2k+1 and
parent is at floor(k/2)
20
ASET
For 25 nodes 31
21
Binary Tree representation ASET
• Linked Representation
– The binary tree is stored in the memory, in the form of a
linked list where the number of nodes are stored at non-
contiguous memory locations and linked together by inheriting
parent child relationship like a tree.
– Each binary tree has a root pointer which points to the root
node of the binary tree.
– In an empty binary tree, the root pointer will point to null.
22
ASET
Note:
1. Left pointer stores the address of the left child while the
right pointer stores the address of the right child.
2. The leaf node contains null in its left and right pointers.
3. There is a special pointer maintained in the memory which
points to the root node of the tree. 23
ASET
24
Quick Revision ASET
If two trees have same structure and but different node content, then they are called ___
(A) Synonyms trees
(B) Joint trees
(C) Equivalent trees
(D) Similar trees
If two trees have same structure and node content, then they are called ____
(A) Synonyms trees
(B) Joint trees
(C) Equivalent trees
(D) Similar trees
The number of edges from the root to the node is called __________ of the tree.
(A) Height
(B) Depth
(C) Length
(D) Width
Thank You..☺
27
ASET
Module-IV
Trees
Syllabus ASET
4
Student Learning Outcomes: ASET
Post-order
In-order
Pre-order
6
Binary Tree Traversal ASET
• Pre-order Traversal
– Traverse the root first then traverse into the left sub-tree and right
sub-tree respectively.
– This procedure will be applied to each sub-tree of the tree recursively.
• In-order Traversal
– Traverse the left sub-tree first, and then traverse the root and the
right sub-tree respectively.
– This procedure will be applied to each sub-tree of the tree recursively.
• Post-order Traversal
– Traverse the left sub-tree and then traverse the right sub-tree and
root respectively.
– This procedure will be applied to each sub-tree of the tree recursively
• Level order traversal
– Nodes are traversed level by level
7
Pre-Order Traversal ASET
8
Pre-order traversal ASET
• Example 2
9
Algorithm for Pre-order ASET
traversal
Step 1: Repeat Steps 2 to 4 while TREE !=
NULL
Step 2: Write TREE -> DATA
Step 3: PREORDER(TREE -> LEFT)
Step 4: PREORDER(TREE -> RIGHT)
[END OF LOOP]
Step 5: END
void preorder(struct treenode *tree)
{
if(tree != NULL)
{
printf("%d",tree→ root);
pre-order(tree→ left);
pre-order(tree→ right);
}
}
10
In-order Traversal ASET
11
ASET
• Example 2
12
Algorithm for In-order ASET
traversal
Step 1: Repeat Steps 2 to 4 while TREE !=
NULL
Step 2: INORDER(TREE -> LEFT)
Step 3: Write TREE -> DATA
Step 4: INORDER(TREE -> RIGHT)
[END OF LOOP]
Step 5: END
void in-order(struct treenode *tree)
{
if(tree != NULL)
{
in-order(tree→ left);
printf("%d",tree→ root);
in-order(tree→ right);
}
}
13
Post order traversal ASET
14
ASET
15
Algorithm for Post-order ASET
traversal
Step 1: Repeat Steps 2 to 4 while TREE !=
NULL
Step 2: POSTORDER(TREE -> LEFT)
Step 3: POSTORDER(TREE -> RIGHT)
Step 4: Write TREE -> DATA
[END OF LOOP]
Step 5: END
void post-order(struct treenode *tree)
{
if(tree != NULL)
{
post-order(tree→ left);
post-order(tree→ right);
printf("%d",tree→ root);
}
}
16
Level order traversal ASET
Level 0
Level 1
Level 2
Level 3
D E T Y K S H J
using Queue
1. Insert a root node in the queue
2. Delete a node from the queue and visit it
3. Insert left child of visited node in the queue
4. Insert right child of the visited node n the queue
5. Repeat steps 2,3 and 4 till queue becomes empty
Queue D K
YE TS
Level order
traversal
D E T
18
ASET
19
Height of a binary tree ASET
20
Function for finding height ASET
of tree
21
Quick Revision ASET
a) 2, 7, 2, 6, 5, 11, 5, 9, 4
b) 2, 7, 5, 2, 6, 9, 5, 11, 4
c) 2, 5, 11, 6, 7, 4, 9, 5, 2
d) 2, 7, 5, 6, 11, 2, 5, 4, 9
2. Consider the following data. The pre order traversal of a binary tree is A, B, E, C, D.
The in order traversal of the same binary tree is B, E, A, D, C. The level order sequence
for the binary tree is _________
a) A, C, D, B, E
b) A, B, C, D, E
c) A, B, C, E, D
d) D, B, E, A, C
Quick Revision ASET
3. Consider the following data and specify which one is Preorder Traversal Sequence,
Inorder and Postorder sequences.
S1: N, M, P, O, Q
S2: N, P, Q, O, M
S3: M, N, O, P, Q
a) S1 is preorder, S2 is inorder and S3 is postorder
b) S1 is inorder, S2 is preorder and S3 is postorder
c) S1 is inorder, S2 is postorder and S3 is preorder
d) S1 is postorder, S2 is inorder and S3 is preorder
a) 2, 7, 2, 6, 5, 11, 5, 9, 4
b) 2, 7, 5, 2, 11, 9, 6, 5, 4
c) 2, 5, 11, 6, 7, 4, 9, 5, 2
d) 2, 7, 5, 6, 11, 2, 5, 4, 9
Quick Revision ASET
5. In a binary search tree, which of the following traversals would print the numbers in
the ascending order?
a) Level-order traversal
b) Pre-order traversal
c) Post-order traversal
d) In-order traversal
a) P Q R S T U V W X
b) W R S Q P V T U X
c) S W T Q X U V R P
d) S T W U X V Q R P
ASET
Thank You..☺
25
ASET
Module-IV
Trees
Syllabus ASET
4
Student Learning Outcomes: ASET
Binary Search tree can be defined as a class of binary trees, in which the
nodes are arranged in a specific order.
This is also called ordered binary tree.
1.In a binary search tree, the value of all the nodes in the left sub-tree is
less than the value of the root.
2.Similarly, value of all the nodes in the right sub-tree is greater than or
equal to the value of the root.
3.This rule will be recursively applied to all the left and right sub-trees of
the root.
4.Left and right sub-trees are also binary tree
6
Example ASET
7
Traversal in a binary ASET
search tree
Preorder: 70 40 35 30 37 50 55 80 75 89 82 93
(Traverse the root first then traverse into
the left sub-tree and right sub-tree
respectively.)
8
Traversal in a binary ASET
search tree
Postorder: 30 37 35 55 50 40 75 82 93 89 80 70
(Traverse the left sub tree first then
traverse into the right sub-tree and then
root.)
9
Traversal in a binary ASET
search tree
Inorder: 30 35 37 40 50 55 70 75 80 82 89 93
(Traverse the left sub tree first then root
and then right sub-tree respectively.)
10
Traversal in a binary ASET
search tree
level-order: 70 40 80 35 50 75 89 30 37 55 82 93
(Traverse each level from left to right)
11
Searching in a Binary ASET
Search Tree
Let x is the key to be searched.
Search 37 in the given tree
Start at the root node and move down the tree
Search 77 in the given tree
• If x is equal to the key in the current node
Search is successful
search tree
1. Searching become very efficient in a binary search tree since, we get a
hint at each step, about which sub-tree contains the desired element.
2. The binary search tree is considered as efficient data structure in compare
to arrays and linked lists.
3. In searching process, it removes half sub-tree at every step.
4. Searching for an element in a binary search tree takes o(log2n) time. In
worst case, the time it takes to search an element is 0(n).
5. It also speed up the insertion and deletion operations as compare to that
in array and linked list.
13
Iterative function for ASET
14
14
Recursive function for searching ASET
in a binary search tree
p= search(root,x);
if (p==NULL) struct node *search(struct node *p, int x)
printf(“key not found\n”); {
else if(p==NULL)
printf(“key found\n”); return NULL;
if (x< p→info)
return search(p=p→ lchild,x);
if (x> p→info)
return search(p=p→ rchild,x);
return p;
}
15
Nodes with Minimum and ASET
Maximum Key
• Nodes with smallest key
– Last node in the leftmost path starting from root
• Node with largest Key
– Last node in the rightmost path starting from root
16
Example ASET
17
Iterative function for Nodes with
ASET
Minimum and Maximum Key
18
Recursive function for Nodes with
ASET
Minimum and Maximum Key
19
Insertion in a binary search ASET
tree
1. Allocate the memory for tree.
2. Set the data part to the value and set the left and right pointer of
tree, point to NULL.
3. If the item to be inserted, will be the first element of the tree,
then the left and right of this node will point to NULL.
4. Else, check if the item is less than the root element of the tree, if
this is true, then recursively perform this operation with the left of
the root.
5. If this is false, then perform this operation recursively with the
right sub-tree of the root.
20
ASET
Step 1:
IF TREE = NULL
Allocate memory for TREE
SET TREE -> DATA = ITEM
SET TREE -> LEFT = TREE -> RIGHT = NULL
ELSE
IF ITEM < TREE -> DATA
Insert(TREE -> LEFT, ITEM)
ELSE
Insert(TREE -> RIGHT, ITEM)
[END OF IF]
[END OF IF]
Step 2:
END
21
ASET
22
Deletion in a binary search ASET
tree
• The node to be deleted is a leaf node
– Replace the leaf node with the NULL and simple free the
allocated space.
23
ASET
24
ASET
• The node to be deleted has two children.
– the node which is to be deleted, is replaced with its in-order successor
or predecessor recursively until the node value (to be deleted) is placed
on the leaf of the tree.
– After the procedure, replace the node with NULL and free the allocated
space.
– Example
• the node 50 is to be deleted which is the root node of the tree. The in-order traversal of
the tree given below.
6, 25, 30, 50, 52, 60, 70, 75.
• replace 50 with its in-order successor 52. Now, 50 will be moved to the leaf of the tree,
which will simply be deleted.
25
ASET
Create the binary search tree using the following data elements.
43, 10, 79, 90, 12, 54, 11, 9, 50
27
ASET
28
ASET
29
Quick Revision ASET
2. What is the specialty about the in-order traversal of a binary search tree?
a) It traverses in a non increasing order
b) It traverses in an increasing order
c) It traverses in a random fashion
d) It traverses based on priority of the node
a) True
b) False
Quick Revision ASET
2. What is the specialty about the in-order traversal of a binary search tree?
a) It traverses in a non increasing order
b) It traverses in an increasing order
c) It traverses in a random fashion
d) It traverses based on priority of the node
a) True
b) False
Quick Revision ASET
4. The height of a BST is given as h. Consider the height of the tree as the no. of
edges in the longest path from root to the leaf. The maximum no. of nodes possible
in the tree is?
a) 2h-1 -1
b) 2h+1 -1
c) 2h +1
d) 2h-1 +1
a) (4, 7)
b) (7, 4)
c) (8, 3)
d) (3, 8)
ASET
Thank You..☺
33
ASET
Module-IV
Trees
Syllabus ASET
4
Student Learning Outcomes: ASET
6
ASET
7
General Discussion on
ASET
Balance Factor
Balance Factor (k) = height (left(k)) - height (right(k))
Balance Remark
factor
1 The left sub-tree is one level
higher than the right sub-tree.
8
ASET
Complexity
Algorithm Average case Worst case
Space o(n) o(n)
Search o(log n) o(log n)
Insert o(log n) o(log n)
Delete o(log n) o(log n)
Note:
• AVL tree controls the height of the binary search tree by not letting
it to be skewed.
• The time taken for all operations in a binary search tree of height h
is O(h). However, it can be extended to O(n) if the BST becomes
skewed (i.e. worst case).
• By limiting this height to log n, AVL tree imposes an upper bound on
each operation to be O(log n) where n is the number of nodes.
9
Operations on AVL tree ASET
Note:
• AVL tree is also a binary search tree therefore, all
the operations are performed in the same way as
they are performed in a binary search tree.
• Searching and traversing do not lead to the
violation in property of AVL tree.
• Insertion and deletion are the operations which can
violate this property and therefore, they need to be
revisited.
• Every AVL Tree is a binary search tree but every
Binary Search Tree need not be AVL tree.
10
Insertion In AVL Tree ASET
11
AVL Tree Rotations ASET
• In AVL tree, after performing operations like insertion and deletion we need
to check the balance factor of every node in the tree.
• If every node satisfies the balance factor condition then we conclude the
operation otherwise we must make it balanced.
• Whenever the tree becomes imbalanced due to any operation we use
rotation operations to make the tree balanced.
• Rotation operations are used to make the tree balanced.
Rotation is the process of moving nodes either to left or to right to make
the tree balanced.
There are four rotations and they are classified into two types.
12
Single Left Rotation (LL Rotation) ASET
• In LL Rotation, every node moves one position to left from the current
position. To understand LL Rotation, let us consider the following
insertion operation in AVL Tree.
13
Single Right Rotation (RR Rotation) ASET
14
Left Right Rotation (LR Rotation) ASET
15
Right Left Rotation (RL Rotation) ASET
16
Operations on an AVL Tree
ASET
17
Search Operation in AVL Tree
ASET
18
Insertion Operation in AVL Tree
ASET
19
Example ASET
20
Example ASET
21
Example ASET
• Construct an AVL Tree by inserting numbers from 1 to 8.
22
Example ASET
• Construct an AVL Tree by inserting numbers from 1 to 8.
23
Deletion in AVL Tree ASET
24
R0 rotation (Node B has
ASET
balance factor 0 )
• If the node B has 0 balance factor, and the balance factor of node A disturbed
upon deleting the node X, then the tree will be rebalanced by rotating tree
using R0 rotation.
• The critical node A is moved to its right and the node B becomes the root of
the tree with T1 as its left sub-tree. The sub-trees T2 and T3 becomes the left
and right sub-tree of the node A.
25
ASET
26
ASET
• In this case, the node B has balance factor 0, therefore the tree will be
rotated by using R0 rotation as shown in the following image.
• The node B(10) becomes the root, while the node A is moved to its
right. The right child of node B will now become the left child of node A.
27
R1 Rotation (Node B has ASET
balance factor 1)
• R1 Rotation is to be performed if the balance factor of Node B is 1.
• In R1 rotation, the critical node A is moved to its right having sub-trees
T2 and T3 as its left and right child respectively.
• T1 is to be placed as the left sub-tree of the node B.
28
ASET
Example: Delete Node 55 from the AVL tree shown in the following
image.
29
ASET
• Deleting 55 from the AVL Tree disturbs the balance factor of the node 50
i.e. node A which becomes the critical node.
• This is the condition of R1 rotation in which, the node A will be moved to
its right (shown in the image below).
• The right of B is now become the left of A (i.e. 45).
30
R-1 Rotation (Node B has balance
ASET
factor -1)
• R-1 rotation is to be performed if the node B has balance factor -1.
• This case is treated in the same way as LR rotation.
• In this case, the node C, which is the right child of node B, becomes the
root node of the tree with B and A as its left and right child respectively.
• The sub-trees T1, T2 becomes the left and right sub-trees of B whereas,
T3, T4 become the left and right sub-trees of A.
31
ASET
32
ASET
• The node B has balance factor -1. Deleting the node 60, disturbs the
balance factor of the node 50 therefore, it needs to be R-1 rotated. The
node C i.e. 45 becomes the root of the tree with the node B(40) and A(50)
as its left and right child.
33
Quick Revision ASET
2. Figure below is a balanced binary tree. If a node inserted as child of the node R,
how many nodes will become unbalanced?
a) 2
b) 1
c) 3
d) 0
3. A binary tree is balanced if the difference between left and right subtree of every
node is not more than ____
a) 1
b) 3
c) 2
d) 0
Quick Revision ASET
4. The figure shown below is a balanced binary tree. If node P is deleted, which of the
following nodes will get unbalanced?
a) U
b) M
c) H
d) A
5. What will be the height of a balanced full binary tree with 8 leaves?
a) 8
b) 5
c) 6
d) 4
ASET
Thank You…☺
36
ASET
Module-IV
Trees
Syllabus ASET
4
Student Learning Outcomes: ASET
6
Threaded Binary Tree ASET
7
Threaded Binary Tree ASET
• In above binary tree, there are 8 null pointers & actual 6 pointers.
• In all there are 14 pointers.
• We can generalize it that for any binary tree with n nodes there
will be (n+1) null pointers and 2n total pointers.
• The objective here to make effective use of these null pointers.
• A. J. perils & C. Thornton jointly proposed idea to make effective
use of these null pointers.
• According to this idea we are going to replace all the null pointers
by the appropriate pointer values called threads.
• And binary tree with such pointers are called threaded tree.
• In the memory representation of a threaded binary tree, it is
necessary to distinguish between a normal pointer and a thread.
8
Threaded Binary Tree: One way
ASET
9
Threaded Binary Tree: One way
ASET
10
Threaded Binary Tree: Two way
ASET
11
Threaded Binary Tree: Two way
ASET
12
Threaded Binary Tree: Two way
ASET
13
Threaded Binary Tree: Two way
ASET
14
Threaded Binary Tree: Two way
ASET
Structure of Thread BT
• Node structure
– For the purpose of our evaluation algorithm, we assume each node
has five fields:
15
Threaded Binary Tree: Two way
ASET
16
Threaded Binary Tree Traversal
ASET
17
Threaded Binary Tree Traversal
ASET
18
Threaded Binary Tree Traversal
ASET
19
Threaded Binary Tree Traversal
ASET
20
Threaded Binary Tree Traversal
ASET
21
Threaded Binary Tree Traversal
ASET
22
Threaded Binary Tree Traversal
ASET
23
Threaded Binary Tree Traversal
ASET
24
Threaded Binary Tree Traversal
ASET
25
Comparison of Threaded BT
ASET
26
Threaded BT
ASET
27
Quick Revision ASET
Thank You…☺
30
ASET
Module-IV
Trees
Syllabus ASET
4
Student Learning Outcomes: ASET
• In search trees like binary search tree, AVL Tree, Red-Black tree,
etc., every node contains only one value (key) and a maximum of
two children.
• But there is a special type of search tree called B-Tree in which a
node contains more than one value (key) and more than two
children.
• B-Tree was developed in the year 1972 by Bayer and McCreight
with the name Height Balanced m-way Search Tree. Later it was
named as B-Tree.
• B-Tree can be defined as follows.
6
B - Tree ASET
7
B - Tree ASET
8
Operations on a B-Tree ASET
9
Search Operation in B-Tree
ASET
The search operation in B-Tree is similar to the search operation in Binary Search
Tree. In a Binary search tree, the search process starts from the root node and we
make a 2-way decision every time (we go to either left subtree or right subtree). In B-
Tree also search process starts from the root node but here we make an n-way
decision every time. Where 'n' is the total number of children the node has. In a B-
Tree, the search operation is performed with O(log n) time complexity. The search
operation is performed as follows...
Step 1 - Read the search element from the user.
Step 2 - Compare the search element with first key value of root node in the tree.
Step 3 - If both are matched, then display "Given node is found!!!" and terminate the
function
Step 4 - If both are not matched, then check whether search element is smaller or
larger than that key value.
Step 5 - If search element is smaller, then continue the search process in left
subtree.
Step 6 - If search element is larger, then compare the search element with next key
value in the same node and repeate steps 3, 4, 5 and 6 until we find the exact match
or until the search element is compared with last key value in the leaf node.
Step 7 - If the last key value in the leaf node is also not matched then display
"Element is not found" and terminate the function. 10
Insertion Operation in B-Tree
ASET
12
Example ASET
13
Example ASET
14
Example ASET
15
Example ASET
16
Quick Revision ASET
1. B-tree of order n is a order-n multiway tree in which each non-root node contains
__________
a) at most (n – 1)/2 keys
b) exact (n – 1)/2 keys
c) at least 2n keys
d) at least (n – 1)/2 keys
2. B-tree and AVL tree have the same worst case time complexity for insertion and
deletion.
a) True
b) False
3. Statement 1: When a node is split during insertion, the middle key is promoted to the
parent as well as retained in right half-node.
Statement 2: When a key is deleted from the leaf, it is also deleted from the non-leaf
nodes of the tree.
1. Statement 1 is true but statement 2 is false
2. Statement 2 is true but statement 1 is false
3. Both the statements are true
4. Both the statements are false
ASET
Thank You…☺
18
ASET
1
ASET
Module-V
Searching & Sorting Techniques
Contents to be Covered
ASET
➢ Insertion Sort
➢ Bubble Sort
➢ Selection Sort
Learning Objectives ASET
8 12 4 6 9 3
8 12 4 6 9 3
ASET
4 5 6 8 9 12 3
3 4 5 6 8 9 12
Bubble Sort algorithm
ASET
4 5 6 3 8 9 12
4 5 3 6 8 9 12
ASET
3 4 5 6 8 9 12
3 4 5 6 8 9 12
Selection Sort ASET
ASET
ASET
ASET
Work for you…. ASET
• https://www.cs.usfca.edu/~galles/visualization/Search.html
(Final) for linear search and binary search
• https://blog.penjee.com/binary-vs-linear-search-animated-gifs/
(for linear search and binary search comparisons)
• https://www.cs.usfca.edu/~galles/visualization/Algorithms.html
• http://www.cs.armstrong.edu/liang/animation/web/BubbleSort.
html (Bubble Sort)
• http://www.ee.ryerson.ca/~courses/coe428/sorting/bubblesort.
html (bUBBLE SORT)
• https://courses.cs.vt.edu/csonline/Algorithms/Lessons/Insertio
nCardSort/insertioncardsort.swf (Insertion sort final)
• http://www.ee.ryerson.ca/~courses/coe428/sorting/insertionso
rt.html (INSERTION SORT ADDITIONAL)
ASET
Thank you
29
ASET
1
ASET
Module-V
Searching & Sorting Techniques
Contents to be Covered
ASET
➢ Quick Sort
➢ Merge Sort
➢ Heap Sort
Learning Objectives ASET
➢ Implement quick sort, merge sort and heap sort algorithms for
complex problems.
Quick Sort ASET
5
Quicksort ASET
• Partition
– Choose a pivot
– Find the position for the pivot so that
• all elements to the left are less / equal
• all elements to the right are equal / greater
6
Quicksort ASET
• Conquer
– Apply the same algorithm to each half
< pivot > pivot
8
ASET
46, 33, 26, 47, 17, 19, 35, 43, 42, 18, 47, 23, 12, 39, 49, 14, 32, 19, 27, 35
9
ASET
46, 33, 26, 47, 17, 19, 35, 43, 42, 18, 47, 23, 12, 39, 49, 14, 32, 19, 27, 35
10
ASET
46, 33, 26, 47, 17, 19, 35, 43, 42, 18, 47, 23, 12, 39, 49, 14, 32, 19, 27, 35
11
ASET
12
ASET
13
ASET
14
ASET
15
ASET
16
ASET
17
ASET
18
ASET
19
ASET
20
ASET
21
ASET
22
ASET
23
ASET
24
Quicksort ASET
• Implementation
quicksort( void *a, int low, int high )
{
int pivot;
/* Termination condition! */
if ( high > low )
{
pivot = partition( a, low, high ); Divide
quicksort( a, low, pivot-1 );
quicksort( a, pivot+1, high ); Conquer
}
}
Quicksort - Partition
ASET
int partition( int *a, int low, int high ) {
int left, right;
int pivot_item;
pivot_item = a[low];
pivot = left = low;
right = high;
while ( left < right ) {
/* Move left while item < pivot */
while( a[left] <= pivot_item ) left++;
/* Move right while item > pivot */
while( a[right] > pivot_item ) right--;
if ( left < right ) {
SWAP(a,left,right); left++; right--;
}
}
/* right is final position for the pivot */
a[low] = a[right];
a[right] = pivot_item;
return right;
} 26
Quicksort - Analysis ASET
• Partition
– Check every item once O(n)
• Conquer
– Divide data in half O(log2n)
• Total
– Product O(n log n)
• Same as Heapsort
– quicksort is generally faster
• Fewer comparisons
27
Quicksort vs Heap Sort ASET
Quicksort
◦ Generally faster
◦ Sometimes O(n2)
Better pivot selection reduces probability
◦ Use when you want average good performance
Commercial applications, Information systems
Heap Sort
◦ Generally slower
◦ Guaranteed O(n log n)
28
Merge Sort - Definition ASET
29
Merge Sort – Divide-and- ASET
Conquer
Divide-and-conquer is a general algorithm
design paradigm:
◦ Divide: divide the input data S in two disjoint
subsets S1 and S2
◦ Conquer: solve the sub-problems associated
with S1 and S2 recursively
◦ Combine: combine the solutions for S1 and
S2 into a solution for S
The base case for the recursion are sub-
problems of size 0 or 1
30
Merge Sort Tree ASET
31
Merge Sort - example ASET
Partition
7294|3861
32
Merge Sort - example ASET
7294|3861
72|94
33
Merge Sort - example ASET
7294|3861
72|94
7|2
34
Merge Sort - example ASET
7294|3861
72|94
7|2
7→7
35
Merge Sort - example ASET
7294|3861
72|94
7|2
7→7 2→2
36
Merge Sort - example ASET
Merge
7294|3861
72|94
7|2 → 2 7
7→7 2→2
37
Merge Sort - example ASET
7294|3861
72|94
7|2 → 2 7 9|4 → 4 9
38
Merge Sort - example ASET
Merge
7294|3861
72|94 → 2 4 7 9
7|2 → 2 7 9|4 → 4 9
39
Merge Sort - example ASET
7294|3861
72|94 → 2 4 7 9 3 8 6 1→1 3 8 6
40
Merge Sort - example ASET
Merge
7294|3861 → 12346789
72|94 → 2 4 7 9 3 8 6 1→1 3 8 6
41
Merge Sort - analysis ASET
42
Merge Sort – sample ASET
code
void mergesort(int low, int
high)
{
if (low<high)
{
int middle=(low+high)/2;
mergesort(low, middle);
mergesort(middle+1,
high);
merge(low, middle,
high); 43
ASET
44
Heap data structure ASET
• Binary tree
• Balanced
• Left-justified or Complete
• Recall:
– The depth of a node is its distance from the root
– The depth of a tree is the depth of the deepest
node
• A binary tree of depth n is balanced if all the
nodes at depths 0 through n-2 have two
children
n-2
n-1
n
Balanced Balanced Not balanced
46
Left-justified binary trees ASET
47
Building up to heap sort ASET
48
The heap property ASET
8 3 8 12 8 14
Blue node has Blue node has Blue node does not
heap property heap property have heap property
• All leaf nodes automatically have the heap
property
• A binary tree is a heap if all nodes in it have
the heap property 49
shiftUp ASET
12 14
8 14 8 12
Blue node does not Blue node has
have heap property heap property
50
Constructing a heap I ASET
51
Constructing a heap II ASET
52
Constructing a heap III ASET
8 8 10 10
10 8 8 5
1 2 3
10 10 12
8 5 12 5 10 5
12 8 8
4
53
Other children are not affectedASET
12 12 14
10 5 14 5 12 5
8 14 8 10 8 10
• The node containing 8 is not affected because its parent gets larger,
not smaller
• The node containing 5 is not affected because its parent gets larger,
not smaller
• The node containing 8 is still not affected because, although its parent
got smaller, its parent is still greater than it was originally
54
A sample heap ASET
22 17
19 22 14 15
18 14 21 3 9 11
22 17
19 22 14 15
18 14 21 3 9 11
22 17
19 22 14 15
18 14 21 3 9
• Now the left child of the root (still the number 11)
lacks the heap property
22
11 17
19 22 14 15
18 14 21 3 9
• Now the right child of the left child of the root (still the
number 11) lacks the heap property:
22
22 17
19 11 14 15
18 14 21 3 9
22 17
19 21 14 15
18 14 11 3 9
62
Analysis ASET
Thank you
65
ASET
1
ASET
Module-V
Searching & Sorting Techniques
Contents to be Covered
ASET
5
Shell Sort ASET
6
Shell Sort ASET
7
How shell sort works? ASET
8
How shell sort works? ASET
9
How shell sort works? ASET
10
How shell sort works? ASET
• We see that it
required only four
swaps to sort the rest
of the array. 11
Shell sort algorithm ASET
Algorithm
Following is the algorithm for shell sort.
Step 1 − Initialize the value of h
Step 2 − Divide the list into smaller sub-list of equal
interval h
Step 3 − Sort these sub-lists using insertion sort
Step 4 − Repeat until complete list is sorted
12
Shell sort pseudo code ASET
13
Shell sort ASET
INPUT 1
OUTPUT
INPUT 2
( )
6
2 N log 2 N + 1
8,9
PASS 3
1,2
• Idea: Divide and 2,3
3,4
conquer: sort subfiles and 4,5
8-page runs
merge 6,6
7,8
9
General External Merge Sort ASET
INPUT 1
INPUT 2
... ... OUTPUT ...
INPUT B-1
Disk Disk
B Main memory buffers
Cost of External Merge Sort ASET
1 + log B −1 N / B
• Number of passes:
• Cost = 2N * (# of passes)
• E.g., with 5 buffer pages, to sort 108 page file:
– Pass 0: 108 / 5 = 22 sorted runs of 5 pages each
(last run is only 3 pages)
– Pass 1: 22 / 4 = 6 sorted runs of 20 pages each
(last run is only 8 pages)
– Pass 2: 2 sorted runs, 80 pages and 28 pages
– Pass 3: Sorted file of 108 pages
Number of Passes of External Sort ASET
INPUT 1
INPUT 1'
INPUT 2
OUTPUT
INPUT 2'
OUTPUT'
b
block size
Disk INPUT k
Disk
INPUT k'
Thank you
26
ASET
1
ASET
Module-V
Searching & Sorting Techniques
Contents to be Covered
ASET
➢ Linear Search
➢ Binary Search
Learning Objectives ASET
problems.
ASET
5
ASET
Sorted Array
6
ASET
Unsorted Array
7
ASET
What is Searching?
9
ASET
Linear search
Linear search
11
ASET
Linear search
12
ASET
14
ASET
In the best case, the target value is in the first element of the
array.
Binary search
• The general term for a smart search through sorted data is
a binary search.
Step 1: The initial search region is the whole array.
Step 2: Look at the data value in the middle of the search
region.
Step 3: If you’ve found your target, stop.
Step 4: If your target is less than the middle data value, the
new search region is the lower half of the data.
Step 5: If your target is greater than the middle data value,
the new search region is the higher half of the data.
Step 6: Continue from Step 2.
18
ASET
Binary search
19
ASET
Binary search
20
ASET
Binary search
21
ASET
Binary search
22
ASET
23
ASET
24
ASET
Important differences
• Input data needs to be sorted in Binary Search and not in
Linear Search
Thank you
27
ASET
1
ASET
Module-V
Searching & Sorting Techniques
Contents to be Covered
ASET
➢ Hashing
➢ Hash Function
➢ Collision Resolution Techniques
Learning Objectives ASET
• Sorting Algorithms
– Elementary
• Insertion Sort
• Selection Sort
• Bubble Sort
– Efficient
• Shell Sort
• Heap Sort
• Quick Sort
• Merge Sort
• Radix Sort
Searching so far ASET
• Truncation
– Ignore a part of the key value and use the remainder
as the table index
• e.g., 21296876 maps to 976
• Folding:
– Partition the key, then combine the parts in some
simple manner
• e.g., 21296876 maps to 212 + 968 + 76 = 1256 and then mod to 256
• Modular Arithmetic:
– Convert the key to an integer, and then mod that
integer by the size of the table
• e.g., 21296876 maps to 876
Truncation Caution ASET
a b c d
a b c c d
a b c c d c
Thank you
26
Amity School of Engineering Technology
1
Syllabus of Module VI Amity School of Engineering Technology
• Introduction:
– Graph Theory Terminology,
– Sequential Representation of Graph (Adjacency and Path Matrix),
– Warshall’s Algorithm,
– Linked Representation of Graph,
– Different Operations on Graphs,
– Traversing A Graph(DFS, BFS),
• Spanning Trees -Introduction
– Representation of Spanning tree,
– Constructing A Spanning Tree(Prim’s Algorithm, Kruskal’s Algorithm).
2
Learning outcomes Amity School of Engineering Technology
2
O( N )
Graph terminology Amity School of Engineering Technology
• Array-based implementation
– A 1D array is used to represent the vertices
– A 2D array (adjacency matrix) is used to
represent the edges
Amity School of Engineering Technology
Array-based implementation
Graph implementation Amity School of Engineering Technology
• Linked-list implementation
– A 1D array is used to represent the vertices
– A list is used for each vertex v which contains
the vertices which are adjacent from v
(adjacency list)
Linked-list implementation
Amity School of Engineering Technology
Amity School of Engineering Technology
Thank You!
All pairs shortest path Amity School of Engineering Technology
– D(0)=W
– D(n)=D which is the goal matrix
1 2 3
1 0 4 5
W= D0 =
2 2 0
1 5
3 -3 0
4 2 3
1 2 3
2 -3 1 0 0 0
P= 2 0 0 0
3 0 0 0
Floyd’s Algorithm 5
Amity School of Engineering Technology
1 5 1 2 3
4 3 1 0 4 5
2
D0 = 2 2 0
-3 D1[2,3] = min( D0[2,3], D0[2,1]+D0[1,3] )
2
3 -3 0
= min (, 7)
1 2 3 =7
1 0 4 5
D1 =
2 2 0 7
D1[3,2] = min( D0[3,2], D0[3,1]+D0[1,2] )
3 -3 0 = min (-3,)
1 2 3 = -3
1 0 0 0
P= 2 0 0 1
3 0 0 0
1 2 3
D1 = 1 0 4 5 Amity School of Engineering Technology
2 2 0 7
3 -3 0
1 2 3
1 0 4 5 D2[1,3] = min( D1[1,3], D1[1,2]+D1[2,3] )
2
D = = min (5, 4+7)
1 5 2 2 0 7
=5
3 -1 -3 0
4 2 3
-3
2 1 2 3
1 0 0 0 D2[3,1] = min( D1[3,1], D1[3,2]+D1[2,1] )
P= 2 0 0 1 = min (, -3+2)
3 2 0 0 = -1
Floyd’s Algorithm 7
D2 = 1 2 3
1 0 4 5 Amity School of Engineering Technology
2 2 0 7
1 5 3 -1 -3 0
4 2 3
1 2 3
-3
2 1 0 2 5 D3[1,2] = min(D2[1,2], D2[1,3]+D2[3,2] )
D3 =
2 2 0 7 = min (4, 5+(-3))
3 -1 -3 0 =2
1 2 3
1 0 3 0 D3[2,1] = min(D2[2,1], D2[2,3]+D2[3,1] )
= min (2, 7+ (-1))
P= 2 0 0 1 =2
3 2 0 0
Floyd’s Algorithm 8
Amity School of Engineering Technology
Floyd’s Algorithm 10
Amity School of Engineering Technology
Floyd’s Algorithm 13
Amity School of Engineering Technology
Floyd’s Algorithm 14
The call tree for Path(1, 4) Amity School of Engineering Technology
Path(1, 4)
Path(1, 6) Path(6, 4)
Print
P(1, 6)=0 v6
Thank You!
Amity School of Engineering Technology
1
Syllabus of Module VI Amity School of Engineering Technology
• Introduction:
– Graph Theory Terminology,
– Sequential Representation of Graph (Adjacency and Path Matrix),
– Warshall’s Algorithm,
– Linked Representation of Graph,
– Different Operations on Graphs,
– Traversing A Graph(DFS, BFS),
• Spanning Trees -Introduction
– Representation of Spanning tree,
– Constructing A Spanning Tree(Prim’s Algorithm, Kruskal’s Algorithm).
2
What is a graph? Amity School of Engineering Technology
• Array-based implementation
– A 1D array is used to represent the vertices
– A 2D array (adjacency matrix) is used to
represent the edges
Amity School of Engineering Technology
Array-based implementation
Graph implementation (cont.) Amity School of Engineering Technology
• Linked-list implementation
– A 1D array is used to represent the vertices
– A list is used for each vertex v which contains
the vertices which are adjacent from v
(adjacency list)
Linked-list implementation
Amity School of Engineering Technology
Adjacency matrix vs. adjacency list
Amity School of Engineering Technology
representation
• Adjacency matrix
– Good for dense graphs --|E|~O(|V|2)
– Memory requirements: O(|V| + |E| ) = O(|V|2 )
– Connectivity between two vertices can be
tested quickly
• Adjacency list
– Good for sparse graphs -- |E|~O(|V|)
– Memory requirements: O(|V| + |E|)=O(|V|)
– Vertices adjacent to another vertex can be
found quickly
Graph specification based on Amity School of Engineering Technology
template<class VertexType>
GraphType<VertexType>::~GraphType()
{
delete [] vertices;
for(int i = 0; i < maxVertices; i++)
delete [] edges[i];
delete [] edges;
delete [] marks; (continues)
}
Amity School
void GraphType<VertexType>::AddVertex(VertexType vertex)of Engineering Technology
{
vertices[numVertices] = vertex;
for(int index = 0; index < numVertices; index++) {
edges[numVertices][index] = NULL_EDGE;
edges[index][numVertices] = NULL_EDGE;
}
numVertices++;
}
template<class VertexType>
void GraphType<VertexType>::AddEdge(VertexType fromVertex,
VertexType toVertex, int weight)
{
int row;
int column;
row = IndexIs(vertices, fromVertex);
col = IndexIs(vertices, toVertex);
edges[row][col] = weight;
} (continues)
Amity School of Engineering Technology
template<class VertexType>
int GraphType<VertexType>::WeightIs(VertexType fromVertex,
VertexType toVertex)
{
int row;
int column;
Graph searching
IF(!found)
Write "Path does not exist"
Amity School of Engineering Technology
start end
(initialization)
Amity School of Engineering Technology
Amity School of Engineering Technology
template <class ItemType> Amity School of Engineering Technology
graph.ClearMarks();
stack.Push(startVertex);
do {
stack.Pop(vertex);
if(vertex == endVertex)
found = true;
(continues)
else { Amity School of Engineering Technology
if(!graph.IsMarked(vertex)) {
graph.MarkVertex(vertex);
graph.GetToVertices(vertex, vertexQ);
while(!vertexQ.IsEmpty()) {
vertexQ.Dequeue(item);
if(!graph.IsMarked(item))
stack.Push(item);
}
}
} while(!stack.IsEmpty() && !found);
if(!found)
cout << "Path not found" << endl;
}
(continues)
Amity School of Engineering Technology
template<class VertexType>
void GraphType<VertexType>::GetToVertices(VertexType vertex,
QueTye<VertexType>& adjvertexQ)
{
int fromIndex;
int toIndex;
Breadth-First-Searching (BFS)
(initialization)
Amity School of Engineering Technology
next:
Amity School of Engineering Technology
Amity School of Engineering Technology
template<class VertexType>
void BreadthFirtsSearch(GraphType<VertexType> graph,
VertexType startVertex, VertexType endVertex);
{
QueType<VertexType> queue;
QueType<VertexType> vertexQ;//
graph.ClearMarks();
queue.Enqueue(startVertex);
do {
queue.Dequeue(vertex);
if(vertex == endVertex)
found = true;
(continues)
else { Amity School of Engineering Technology
if(!graph.IsMarked(vertex)) {
graph.MarkVertex(vertex);
graph.GetToVertices(vertex, vertexQ);
while(!vertxQ.IsEmpty()) {
vertexQ.Dequeue(item);
if(!graph.IsMarked(item))
queue.Enqueue(item);
}
}
}
} while (!queue.IsEmpty() && !found);
if(!found)
cout << "Path not found" << endl;
}
Amity School of Engineering Technology
Single-source shortest-path
problem
• There are multiple paths from a source
vertex to a destination vertex
• Shortest path: the path whose total
weight (i.e., sum of edge weights) is
minimum
• Examples:
– Austin->Houston->Atlanta->Washington:
1560 miles
– Austin->Dallas->Denver->Atlanta-
>Washington: 2980 miles
Amity School of Engineering Technology
Single-source shortest-path
problem (cont.)
• Common algorithms: Dijkstra's
algorithm, Bellman-Ford algorithm
• BFS can be used to solve the shortest
graph problem when the graph is
weightless or all the weights are the
same
(mark vertices before Enqueue)
Amity School of Engineering Technology
Exercises
• 24-37
Learning outcomes Amity School of Engineering Technology
e2 e4
∪ e4 E
C D D e6
e3
Amity School of Engineering Technology
Operations on Graph
2. Intersection If two graph G1 & G2 are given then 𝐺1 ∩ 𝐺2
Will be 𝑉 𝐺1 ∩ 𝐺2 = 𝑉 𝐺1 ∩ 𝑉(𝐺2 )
& 𝐸 𝐺1 ∩ 𝐺2 = 𝐸 𝐺1 ∩ 𝐸(𝐺2 )
e1
A B B e5
e2 e4
∩ e4 E
C D D e6
e3
Amity School of Engineering Technology
Operations on Graph
3. Sum of two graph If two graph G1 & G2 are given then 𝐺1 + 𝐺2
Will be 𝑉 𝐺1 + 𝐺2 = 𝑉 𝐺1 + 𝑉(𝐺2 )
& 𝐸 𝐺1 + 𝐺2 = Edges which are in G1 & G2 and edges
obtained by joining each vertex of G1 to each G2
A B
+
e2 e4
C
D
e3
D
Amity School of Engineering Technology
Operations on Graph
4. Ring Sum If two graph G1 & G2 are given then 𝐺1 ⊕ 𝐺2
Will be 𝑉 𝐺1 ⊕ 𝐺2 = 𝑉 𝐺1 ∪ 𝑉(𝐺2 )
& 𝐸 𝐺1 ⊕ 𝐺2 = 𝐸 𝐺1 ∪ 𝐸 𝐺2 − 𝐸 𝐺1 ∩ 𝐸(𝐺2 )
edges either in G1 or G2 but not in both
e1
A B B e5
e2 e4
∪ e4 E
C D D e6
e3
Amity School of Engineering Technology
Operations on Graph
5. Product If two graph G1 & G2 are given then 𝐺1 × 𝐺2
Will be 𝑉 𝐺1 × 𝐺2 = 𝑉 𝐺1 × 𝑉(𝐺2 )
& 𝐸 𝐺1 × 𝐺2 = 𝐸 𝐺1 × 𝐸 𝐺2 ∪ 𝐸 𝐺2 × 𝐸(𝐺1 )
𝑉 𝐺1 × 𝐺2 = { 𝐴, 0 , 𝐴, 1 , 𝐵, 0 , 𝐵, 1 , 𝐶, 0 , 𝐶, 1 }
A 𝐸 𝐺1 × 𝐺2 = { 𝐴, e4 , 𝐵, e4 , 𝐶, e4 , 0, e2 , 0, e3 ,
0 1, e2 , 1, e3 }
e2 A, e4
A, 0
×
A, 1
e4
B 0, e2 1, e2
B, e4
e3 1 B, 0 B, 1
0, e3 1, e3
C C, e4
C, 0 C, 1
Amity School of Engineering Technology
Operations on Graph
6. Complement 𝐺 → 𝐺 ′
𝐺 ′ is said to be complement when the vertex pair which are
adjacent in 𝐺 ′ are not adjacent in G.
A A
0 1 0 1
B C B C
2 2
𝐺 𝐺′
Amity School of Engineering Technology
Thank You!
Amity School of Engineering Technology
1
Learning outcomes Amity School of Engineering Technology
2
Graph Traversal Amity School of Engineering Technology
Graph Terminology
-Graph Representation
-Warshall Algorithms
-Different Operations on Graphs
-Graph Traversal
-Minimumspanning tree
- Dijkstra shortest Path Algorithm
3
Graph Traversal Amity School of Engineering Technology
4
Amity School of Engineering Technology
5
Amity School of Engineering Technology
9
Amity School of Engineering Technology
1
0
2
3
a Queue and Deque
4. Next vertex in queue is
selected again step 3 is
carried out. Continue till all
vertex been visited
1
5. We have visited all vertex
2 2 3 and also queue is empty.
6. The path we followed is the
v w x y
final Spanning tree.
Q[8] s w r t x v u y
Amity School of Engineering Technology
11
Amity School of Engineering Technology
12
Amity School of Engineering Technology
Complexity Analysis
• Queuing time is O(V) and scanning all edges requires O(E)
• Overhead for initialization is O (V)
• So, total running time is O(V+E)
13
Amity School of Engineering Technology
Thank You
Amity School of Engineering Technology
1
Learning outcomes Amity School of Engineering Technology
2
Amity School of Engineering Technology
3
Amity School of Engineering Technology
4
Amity School of Engineering Technology
MST Algorithm
Kruskal’s Algorithm
Prim’s Algorithm
6
Amity School of Engineering Technology
Example
A cable company want to connect five villages to their network which
currently extends to the market town of Avonford. What is the minimum
length of cable needed? 5
BrinleighB 5 Cornwell
C
5
5
44
22
7
Edan
E
Amity School of Engineering Technology
Kruskal’s Algorithm
1. Remove all loops & Parallel Edges from the given graph
2. Sort all the edges in non-decreasing order of their weight.
3. Pick the smallest edge. Check if it forms a cycle with the
spanning tree formed so far. If cycle is not formed, include
this edge. Else, discard it.
4. Repeat step#2 until there are (V-1) edges in the spanning
tree
9
Amity School of Engineering Technology
Prim’s Algorithm
1. Create a set mstSet that keeps track of vertices already included in
MST.
2. Assign a key value to all vertices in the input graph. Initialize
all key values as INFINITE. Assign key value as 0 for the first
vertex so that it is picked first.
3. While mstSet doesn’t include all vertices
Pick a vertex u which is not there in mstSet and has minimum key value.
Include u to mstSet
Update key value of all adjacent vertices of u. To update the key values, iterate through all
adjacent vertices. For every adjacent vertex v, if weight of edge u-v is less than the previous
key value of v, update the key value as weight of u-v
11
Amity School of Engineering Technology
Thank You !