DS New
DS New
SYLLABUS
e Name: data structures Course Code:
h, Year – Sem : IT,II-I Regulation:R-19
mic year:2022-23 Faculty :
I
tructures - Definition, Classification of Data Structures, Operations on Data Structures, Abstract Data Type (ADT),
naries of algorithms. Time and Space complexity.
ing - Linear search, Binary search, Fibonacci search.
- Insertion sort, Selection sort, Exchange (Bubble sort, quick sort), distribution (radix sort), merging (Merge sort)
hms.
II
List: Introduction, Single linked list, Representation of Linked list in memory, Operations on Single Linked list-
on, Deletion, Search and Traversal ,Reversing Single Linked list, Applications on Single Linked list- Polynomial
sion Representation ,Addition and Multiplication, Sparse Matrix Representation using Linked List, Advantages and
antages of Single Linked list, Double Linked list-Insertion, Deletion, Circular Linked list-Insertion, Deletion.
III
s: Introduction to Queues, Representation of Queues-using Arrays and using Linked list, Implementation of Queues-using
and using Linked list, Application of Queues-Circular Queues, Deques, Priority Queues, Multiple Queues.
Introduction to Stacks, Array Representation of Stacks, Operations on Stacks, Linked list Representation of Stacks,
ions on Linked Stack, Applications-Reversing list, Factorial Calculation, Infix to Postfix Conversion, Evaluating Postfix
sions.
IV
Basic Terminology in Trees, Binary Trees-Properties, Representation of Binary Trees using Arrays and Linked lists.
Search Trees- Basic Concepts, BST Operations: Insertion, Deletion, Tree Traversals, Applications-Expression Trees,
ort, Balanced Binary Trees- AVL Trees, Insertion, Deletion and Rotations.
V
: Basic Concepts, Representations of Graphs-Adjacency Matrix and using Linked list,
Traversals
& DFT), Applications- Minimum Spanning Tree Using Prims & Kruskals Algorithm,
a’s shortest path,
ive closure, Warshall’s Algorithm.
ooks:
Structures Using C. 2nd Edition.Reema Thareja, Oxford.
Structures and algorithm analysis in C, 2nded, Mark Allen Weiss.
nce Books:
damentals of Data Structures in C, 2nd Edition, Horowitz, Sahni, Universities Press.
Structures: A PseudoCode Approach, 2/e, Richard F.Gilberg, Behrouz A. Forouzon, Cengage.
Structures with C, Seymour Lipschutz TMH
urces:
//algs4.cs.princeton.edu/home/
://faculty.washington.edu/jstraub/dsa/Master_2_7a.pdf
Course Coordinator(s):
Module Coordinator Program Coordinator HOD
Course Objectives:
The objective of the course is to
Introduce the fundamental concept of data structures and abstract data types
Emphasize the importance of data structures in developing and implementing efficient algorithms
Describe how arrays, records, linked structures, stacks, queues, trees, and graphs are represented in memory and used by
algorithms
Course Outcomes:
After completing this course a student will be able to:
Summarize the properties, interfaces, and behaviors of basic abstract data types
Discuss the computational efficiency of the principal algorithms for sorting & searching
Use arrays, records, linked structures, stacks, queues, trees, and Graphs in writing programs
Demonstrate different methods for traversing trees
AVG 1 - - - - - - - - 2 -
. .
2.8 8 1.4 1 6 1
Note:Enter Correlation levels 1,2 or 3 as defined below:
1: Slightly(Low) 2: Moderate(Medium) 3:
Correlation
CO PO/PSO Justification (including CO statement)
Level
CO-1: Describe mathematical methods to analyze the performance of an
CO-
PO1 3 algorithm using asymptotic notations. Requires a strong foundation in
1
mathematical and algorithmic principles.
Analytical skills are required to evaluate algorithm efficiency, aligning with
CO-1 PO2 2
PO2.
CO-1 PO3 1 Basic design skills are applied while comparing algorithm performances.
Learning about performance analysis supports lifelong learning and
CO-1 PO12 1
upskilling.
CO-1 PSO1 3 Asymptotic analysis is fundamental in computing, directly supporting PSO1.
Slight relevance when algorithm performance impacts domain-specific
CO-1 PSO2 1
solutions.
CO-2: Apply various algorithm design techniques (Divide and Conquer,
CO-
PO1 3 Greedy, Dynamic Programming, Backtracking) to solve computational
2
problems efficiently. Strong engineering knowledge is required.
Solving computational problems requires critical thinking and problem
CO-2 PO2 3
analysis, supporting PO2.
Designing efficient algorithms aligns with PO3 (Design/Development of
CO-2 PO3 2
Solutions).
CO-2 PO12 1 Applying algorithm design techniques enhances lifelong learning skills.
CO-2 PSO1 3 Core competency in algorithm design is essential in computing, supporting
Correlation
CO PO/PSO Justification (including CO statement)
Level
PSO1.
CO-2 PSO2 2 Relevant for domain-specific computational solutions.
CO-3: Analyze and compare the performance of algorithms for searching,
CO-
PO1 3 sorting, and graph problems. Strong foundation in algorithmic principles
3
required.
Performance analysis requires analytical and problem-solving skills,
CO-3 PO2 3
supporting PO2.
Comparison of algorithm efficiency aids in designing optimized solutions,
CO-3 PO3 2
aligning with PO3.
CO-3 PO12 1 Understanding algorithm performance contributes to lifelong learning.
CO-3 PSO1 3 Essential for domain competency in computing and software development.
CO-3 PSO2 2 Helps in selecting domain-specific optimal solutions.
CO-4: Design and implement algorithms for NP-hard problems using
CO-
PO1 3 heuristic and approximation techniques. Requires deep understanding of
4
algorithm principles.
CO-4 PO2 3 Problem-solving for NP-hard problems aligns with PO2.
Designing heuristic algorithms directly maps to PO3 (Design/Development of
CO-4 PO3 3
Solutions).
CO-4 PO12 1 Learning heuristic and approximation methods supports lifelong learning.
Developing solutions for complex computational problems is central to
CO-4 PSO1 3
PSO1.
CO-4 PSO2 2 Heuristic techniques can be applied in domain-specific scenarios.
CO-5: Evaluate the suitability of different algorithms and data structures for
CO-
PO1 3 real-world applications and optimize them for performance. Strong
5
knowledge of algorithms and data structures required.
Analytical skills are needed to evaluate and compare algorithms, aligning
CO-5 PO2 3
with PO2.
Selecting and optimizing algorithms supports PO3 (Design/Development of
CO-5 PO3 3
Solutions).
CO-5 PO12 1 Evaluation and optimization promote continuous learning.
CO-5 PSO1 3 Core competency in choosing efficient solutions aligns with PSO1.
CO-5 PSO2 2 Helps in applying optimal algorithms in domain-specific applications.
Course Coordinator(s)
ACADEMIC CALENDAR
TEACHING/INSTRUCTIONAL PLAN
Course Name: DATA STRUCTURESCourse Code: Regulation:R20A
Branch, Year – Sem: I.T, IV B.Tech. I Sem Faculty:
Academic year:2020-21
No. of
Teaching
UNITS TOPICS Classes Teaching Aids
Methods
Planned
Introduction PPTs
Lecture
01 LCD Projector
Whiteboard
Definition, PPTs
Classification of Lecture LCD Projector
Data Structures, 02
Whiteboard
Preliminaries of PPTs
algorithms Lecture LCD Projector
01
Whiteboard
UNIT-
I Time and Space PPTs
complexity. Lecture LCD Projector
02
Whiteboard
Representation of Lecture
Queues-using Problem PPTs
Arrays Solving LCD Projector
02
Method Whiteboard
, Applications on Lecture
Single Linked list Problem PPTs
02 Solving LCD Projector
Method Whiteboard
Discussion
Introduction to
Queues, PPTs
Lecture
Representation of LCD Projector
01 Discussion
Queues-using Whiteboard
Arrays and using
Linked list
Implementation of PPTs
Queues-using Lecture LCD Projector
Arrays and using 01 Discussion Whiteboard
Linked list
Visual Aids- Images
Application of PPTs
Queues-Circular Lecture
01 LCD Projector
Discussion
Whiteboard
Introduction to PPTs
Stacks, Array Lecture
02 LCD Projector
Representation of Discussion
Whiteboard
Stacks,
Operations on Lecture
Stacks, Linked list PPTs
Discussion
Representation of 02 LCD Projector
Problem
Stacks, Operations Whiteboard
Solving
Applications- PPTs
Reversing list, Lecture
Factorial 02 LCD Projector
Discussion
Calculation, Infix to Whiteboard
Postfix Conversion
UNIT- Trees: Basic Lecture
IV Terminology in Tree PPTs
Discussion
02 LCD Projector
Problem
Whiteboard
Solving
Applications- Lecture
Expression Trees, PPTs
Discussion
Heap Sort 1 LCD Projector
Problem
Whiteboard
Solving
Applications- Lecture
Expression Trees, PPTs
Discussion
Heap Sort, Balanced 1 LCD Projector
Problem
Binary Trees- Whiteboard
Solving
Representations of PPTs
Graphs- Lecture
02 LCD Projector
Discussion
Whiteboard
Minimum PPTs
Lecture
Spanning Tree LCD Projector
01 Discussion
Using Prims Whiteboard
Dijkstra’s Lecture
PPTs
shortest path, Discussion
1 LCD Projector
Problem
Whiteboard
Solving
Total
No. of
60
Classe
s
c. E-Learning YES
2. MOOCS & Open Sources(NPTEL) NO
5. Role Play NO
9. Seminar Method NO
The course outcomes are evaluated using Internal and External assessments as per the following:
CO Attainment level = 20% of Internal Attainment level + 80% of External Attainment level
Theory Courses: Internal attainment level = (50% of DESCRIPTIVE + 33% of OBJECTIVE + 17%
of ASSIGNMENT) attainment levels
Attainment levels in External Examinations:
(a) External Examination – Grade to Marks Conversion for Theory courses
RAN ME GRA
GE AN DE
91- 95 O
100
81-90 85 A
71-80 75 B
61-70 65 C
51-60 55 D
41-50 45 E
40 39 F
RAN ME GRA
GE AN DE
91- 95 O
100
81-90 85 A
71-80 75 B
61-70 65 C
51-60 55 D
41-50 45 E
40 39 F
External examination performance alone is obtained by subtracting final internal marks from the mean marks
obtained as per the grade awarded by University.
Project Work: Attainment level = (20% Internal + 80% External) attainment levels
The attainment of program outcomes (POs) and Program Specific Outcomes (PSOs) is evaluated by
PAC that identifies, collects, and prepares data from assessment processes. The assessment processes are
categorized as per the following.
1. Direct Assessments
2. Indirect Assessments
Direct Assessment Tools and Process:
Direct attainment level of a PO & PSO is determined by taking average across all
courses attainment levels addressing that PO and/or PSO. The average attainment levels of
all courses at program level are calculated as per the process described elsewhere. The PO
and PSO attainment levels are evaluated based on the Program level Course – PO
mapping.
Indirect attainment level of PO & PSO is determined based on the student exit surveys.
This data is generated by administering course and program exit surveys.
The indirect assessment tools along with their assessment criteria are given in Table.
Course Coordinator(s)
Week / 1 2 3 4 5 6 7
Hour
Mon DS
Tue DS
Wed DS
Thu DS
Fri
Sat DS
UNIT 3
1 Define Queue and its types. 1 CO3
2 Convert the infix expression (A+B) * C into postfix. 1 CO3
UNIT 5
1 Explain BFS and DFS with algorithms and examples. 1 CO5
2 1 CO5
v Write and explain Prim’s algorithm for finding MST with an example.
3 Write Kruskal’s algorithm with an example. 2 CO5
4 Explain Dijkstra’s shortest path algorithm with an example. 2 CO5
5 Discuss Warshall’s algorithm for transitive closure. 3 CO5
6 Explain Dijkstra’s shortest path algorithm with an example. 3 CO5
Course Code: Branch, Year – IT, 2 Year nd
Regulation: R 19
DATA STRUCTURES
ASSIGNMENT-1
1. Explain the different notations of algorithm complexity (Big-O, Big-Ω, Big-θ) with examples.
2. Write and explain the algorithm for Merge Sort and analyze its complexity.
3. Explain insertion and deletion operations in a singly linked list with algorithms
4. Differentiate between singly, doubly, and circular linked lists with diagrams.
5. Explain queue implementation using arrays with algorithms.
Course Coordinator(s):
DATA STRUCTURES
ASSIGNMENT-2
Course Coordinator(s):
1. Explain insertion and deletion in a binary search tree (BST) with examples. [4M]
2. Explain the working of Quick Sort with an example. [4M]
3. Explain the drawback of linear queue?
[2M]
Question No. 1 2 3
Course Outcome CO-1 CO-2 CO-3
Marks allotted (Xi) 4 4 2
Bloom’s Taxonomy level 2 2 2
Bloom’s Taxonomy Score
on a Scale of (1-10) (Si) 6 6 6
Bloom’s Index Score
n
∑ X i∗S i
Blooms Index (BI )= i=1n
∑ Xi
i=1
Where ‘n’ are the number of questions in the Internal test paper / Assignment
‘Xi’ is the marks allocated for the ith question as per the assessment plan
‘Si’ is the score allocated for the ith question as per the Blooms Taxonomy score
24+24+12 60
BI = ------------------------------------------ = ---- = 6
10 10
Remarks of
Blooms Attainment
Code Course Faculty Name module
Index Level
coordinator
6
Question No. 1 2 3
Course Outcome CO-1 CO-2 CO-3
Marks allotted (Xi) 2 4 4
Bloom’s Taxonomy level 2 1 2
Bloom’s Taxonomy Score
on a Scale of (1-10) (Si) 7 6 7
Bloom’s Index Score
n
∑ X i∗S i
Blooms Index (BI )= i=1n
∑ Xi
i=1
Where ‘n’ are the number of questions in the Internal test paper / Assignment
‘Xi’ is the marks allocated for the ith question as per the assessment plan
‘Si’ is the score allocated for the ith question as per the Blooms Taxonomy score
14+24+28 66
BI = ------------------------------------------ = ---- = 6.6
10 10
Remarks of
Blooms Attainment
Code Course Faculty Name module
Index Level
coordinator
6.6
Course Coordinator(s)
S.
Name of the Name of the No. of Studen
N Topics Covered Date
Subject Faculty attended
o.
1 CO Register Transfer
08-02-
Bus and Memory
2021
Transfers
24
Computer 09-02-
Instructions, 2021
Instruction Cycle
Data Representation: 10-02-
24
Data types 2021
Computer 11-02-
Arithmetic: Addition 2021 24
and Subtraction
Register Transfer 12-02- 24
Language and Micro 2021
operations
Addressing Modes, 13-02-2021
Data Transfer and 24
Manipulation
SYLLABUS COVERAGE
Unit Prescribed Covered Remarks
date date
Unit 15-11-2021 17-11-2021
1
Unit 19-12-2021 22-12-2021
2
Unit 23-01-2021 25-01-2021
3
Unit 08-02-2021 10-02-2021
4
Unit 22-02-2021 22-02-2021
5
08-02-2021 to
1 Carrier Guidance 1 week
13-02-2021
3 198X1A1203 D 5 3 P
4 198X1A1204 B 7 3 P
5 198X1A1205 C 6 3 P
6 198X1A1206 B 7 3 P
7 198X1A1207 F 0 0 F
8 198X1A1208 B 7 3 P
9 198X1A1209 C 6 3 P
10 198X1A1210 D 5 3 P
11 198X1A1211 F 0 0 F
12 198X1A1212 C 6 3 P
13 198X1A1213 F 0 0 F
14 198X1A1214 D 5 3 P
15 198X1A1215 F 0 0 F
16 198X1A1216 B 7 3 P
17 198X1A1217 C 6 0 F
18 198X1A1218 C 6 3 P
19 198X1A1219 C 6 3 P
20 198X1A1223 C 6 3 P
21 198X1A1224 D 5 3 P
22 198X1A1226 F 0 0 F
23 198X1A1227 F 0 0 F
24 198X1A1228 C 6 3 P
25 198X1A1229 F 0 0 F
26 198X1A1231 C 6 3 P
27 198X1A1232 F 0 0 F
28 198X1A1233 D 5 0 P
29 198X1A1234 D 5 0 P
30 198X1A1235 D 5 0 P
31 198X1A1236 B 7 3 P
32 198X1A1238 D 5 3 P
33 198X1A1240 D 5 3 P
34 198X1A1241 C 6 3 P
35 198X1A1242 F 0 0 F
36 198X1A1243 C 6 3 P
37 198X1A1244 B 7 3 P
38 198X1A1245 F 0 0 F
39 198X1A1246 B 7 3 P
40 198X1A1247 F 0 0 F
41 198X1A1248 B 7 0 F
42 198X1A1249 C 6 3 P
43 198X1A1250 C 6 3 P
44 198X1A1251 F 0 0 F
45 198X1A1252 D 5 3 P
46 198X1A1253 B 7 3 P
47 198X1A1254 C 6 3 P
48 198X1A1255 F 0 0 F
49 198X1A1256 B 7 3 P
50 198X1A1257 C 6 3 P
51 198X1A1258 C 6 3 P
52 198X1A1259 C 6 3 P
53 198X1A1260 D 5 3 P
54 198X1A1261 S 9 3 P
55 198X1A1262 C 6 3 P
56 198X1A1263 F 0 0 F
Course Coordinator(s)
University Results:
Pass % of Students
% Average Marks
Minimum / Maximum
marks
B. Action Taken to Improve the Performance in the current Semester (based on the course closure report in
the previous AY):
C. The student performance has been consistently poor with respect to some COs. Analysis of answer
scripts, exit survey and interaction with the students revealed that this could be attributed to:
5 Principles of Operation of
Multiprocessor Systems and
Nil
Pipelining
Program Coordinator
UNITWISE MATERIALS
UNIT-1
Unit – I
Syllabus:
• Data Structures - Definition, Classification of Data Structures, Operations on Data Structures, Abstract Data
Type (ADT), Preliminaries of algorithms. Time and Space complexity.
• Searching - Linear search, Binary search, Fibonacci search.
• Sorting- Insertion sort, Selection sort, Exchange (Bubble sort, quick sort), distribution (radix sort), merging
(Merge sort) algorithms.
INTRODUCTION:
A data structure is a particular way of storing and organizing data in a computer so that it can be
used efficiently.
Some common examples of data structures are arrays, linked lists, queues, stacks, binary trees, and
hash tables
Today computer programmers do not write programs just to solve a problem but to write an
efficient program.
When selecting a data structure to solve a problem, the following steps must be performed.
1. Analysis of the problem to determine the basic operations that must be supported.
2. Quantify the resource constraints for each operation.
3. Select the data structure that best meets these requirements.
The term data means a value or set of values. It specifies either the value of a variable or a constant
(e.g., marks of students, name of an employee, address of a customer, value of pi, etc.).
A record is a collection of data items. For example, the name, address, course, and marks obtained
are individual data items. But all these data items can be grouped together to form a record.
A file is a collection of related records. For example, if there are 60 students in a class, then there are
60 records of the students. All these related records are stored in a file.
Data structures are generally categorized into two classes: primitive and non-primitive data
structures.
Primitive and Non-primitive Data Structures:
Primitive data structures are the fundamental data
types which are supported by a programming
language. Some basic data types are integer, real,
character, and boolean. The terms ‘data type, basic
data type’, and ‘primitive data type’ are often used
interchangeably.
Non-primitive data structures are those data structures which are created using primitive data
structures. Examples of such data structures include linked lists, stacks, trees, and graphs.
Non-primitive data structures can further be classified into two categories: linear and non-linear
data structures.
If the elements of a data structure are not stored in a sequential order, then it is a non-linear data
structure.
o The relationship of adjacency is not maintained between elements of a non-linear data structure.
Examples include trees and graphs.
Arrays:
An array is a collection of similar data elements. These data elements have the same data type. The
elements of the array are stored in consecutive memory locations and are referenced by an index
(also known as the subscript).
In C, arrays are declared using the following syntax: datatype name[size];
Ex: int marks[10];
limitations:
o Arrays are of fixed size.
o Data elements are stored in contiguous memory locations which may not be always available.
o Insertion and deletion of elements can be problematic because of shifting of elements from their
positions.
Linked Lists:
linked list is a dynamic data structure in which elements (called nodes) form a sequential list.
In a linked list, each node is allocated space as it is added to the list. Every node in the list points to
the next node in the list.
Every node contains the following
The value of the node or any other data that corresponds to that node A pointer or
link to the next node in the list
The first node in the list is pointed by Head/Start/First. The last node in the list contains a NULL
pointer to indicate that it is the end or tail of the list.
Advantage: Easier to insert or delete data elements
Disadvantage: Slow search operation and requires more memory space
Stacks:
A stack is a linear data structure in which insertion and deletion of elements are done at only one
end, which is known as the top of the stack.
Stack is called a last-in, first-out (LIFO) structure
because the last element which is added to the
stack is the first element which is deleted from
the stack.
Stacks can be implemented using arrays or
linked lists.
Every stack has a variable top associated with
it. Top is used to store the address of the
topmost element of the stack.
It is this position from where the element will be added or deleted. There is another variable MAX,
which is used to store the maximum number of elements that the stack can store.
If top = NULL, then it indicates that the stack is empty and if top = MAX–1, then the stack is full.
A stack supports three basic operations: push, pop, and peep. The push operation adds an element
to the top of the stack. The pop operation removes the element from the top of the stack. And the
peep operation returns the value of the topmost element of the stack (without deleting it).
Queues:
A Queue is a linear data structure in which insertion can be done at rear end and deletion of
elements can be dome at front end.
A queue is a first-in, first-out (FIFO) data
structure in which the element that is inserted
first is the first one to be taken out.
Like stacks, queues can be implemented by using either arrays or linked lists.
A queue is full when rear = MAX – 1, An underflow condition occurs when we try to delete an
element from a queue that is already empty. If front = NULL and rear = NULL, then there is no
element in the queue.
Trees:
A tree is a non-linear data structure which consists of a collection of nodes arranged in a
hierarchical order.
One of the nodes is designated as the root node, and the remaining nodes can be partitioned into
disjoint sets such that each set is a sub-tree of the root
The simplest form of a tree is a binary tree. A binary tree consists
of a root node and left and right sub-trees, where both sub-trees
are also binary trees.
Each node contains a data element, a left pointer which points to
the left sub-tree, and a right pointer which points to the right sub-
tree.
The root element is the topmost node which is pointed by a ‘root’
pointer. If root = NULL then the tree is empty.
Here R is the root node and T1 and T2 are the left and right subtrees of R. If T1 is non-empty, then T1
is said to be the left successor of R. Likewise, if T2 is non-empty, then it is called the right successor
of R.
Advantage: Provides quick search, insert, and delete operations
Disadvantage: Complicated deletion algorithm
Graphs:
A graph is a non-linear data structure which is a collection of vertices (also called nodes) and
edges that connect these vertices.
A node in the graph may represent a city and the edges connecting the
nodes can represent roads.
A graph can also be used to represent a computer network where the
nodes are workstations and the edges are the network connections.
Graphs do not have any root node. Rather, every node in the graph can be connected with every
another node in the graph.
Advantage: Best models real-world situations
Disadvantage: Some algorithms are slow and very complex
This section discusses the different operations that can be performed on the various data structures
previously mentioned.
Traversing It means to access each data item exactly once so that it can be processed. For example, to
print the names of all the students in a class.
Searching It is used to find the location of one or more data items that satisfy the given constraint.
Such a data item may or may not be present in the given collection of data items. For example, to
find the names of all the students who secured 100 marks in mathematics.
Inserting It is used to add new data items to the given list of data items. For example, to add the
details of a new student who has recently joined the course.
Deleting It means to remove (delete) a particular data item from the given collection of data items.
For example, to delete the name of a student who has left the course.
Sorting Data items can be arranged in some order like ascending order or descending order
depending on the type of application. For example, arranging the names of students in a class in an
alphabetical order, or calculating the top three winners by arranging the participants’ scores in
descending order and then extracting the top three.
Merging Lists of two sorted data items can be combined to form a single list of sorted data items.
ABSTRACT DATA TYPE:
An abstract data type (ADT) is a data structure, focusing on what it does and ignoring how it does its
job. (or) Abstract Data type (ADT) is a
type (or class) for objects whose behavior is
defined by a set of value and a set of operations.
Ex: stacks ADT and queues ADT. the user is
concerned only with the type of data and the
operations that can be performed on it.
We can implement both these ADTs using an
array or a linked list.
Advantage of using ADTs
Modification of a program is simple, For example, if you want to add a new field to a student’s
record to keep track of more information about each student, then it will be better to replace an
array with a linked structure to improve the program’s efficiency.
In such a scenario, rewriting every procedure that uses the changed structure is not desirable.
Therefore, a better alternative is to separate the use of a data structure from the details of its
implementation.
PRELIMINARIES OF ALGORITHM:
1. Time Complexity:
The time complexity of an algorithm is the amount of computing time required by an algorithm to
run its completion.
There are 2 types of computing time 1. Compile time 2. Run time
The time complexity generally computed at run time (or) execution time.
The time complexity can be calculated in terms of frequency count.
Frequency count is a count denoting the number of times the statement should be executed.
The time complexity can be calculated as
Comments – 0
Assignment / return statement – 1 Conditional (or)
Selection Constructs – 1
2. Space Complexity:
Space Complexity can be defined as amount of memory (or) space required by an Algorithm to run.
To compute the space complexity we use 2 factors i. Constant ii. Instance characteristics.
The space requirement S(p) can be given as S(p) = C+Sp
Where C- Constant, it denotes the space taken for input and output. Sp – Amount
of space taken by an instruction, variable and identifiers.
Example 1: Sum of three numbers
Algorithm Add(a,b,c)
{
//a,b,c are float type variables return a+b+c;
}
The space required for this algorithm is: Assume a,b,c are occupies 1 word size each, total size comes
to be 3.
SEARCHING:
Linear search is a technique which traverse the array sequentially to locate given item or search
element.
In Linear search, we access each element of an array one by one sequentially and see weather it is
desired element or not. We traverse the entire list and match each element of the list with the item
whose location is to be found. If the match found then location of the item is returned otherwise the
algorithm return NULL.
A search is successful then it will return the location of desired element
If A search will unsuccessful if all the elements are accessed and desired element not found.
Linear search is mostly used to search an unordered list in which the items are not
sorted. Linear search is implemented using following steps...
Step 1 - Read the search element from the user.
Step 2 - Compare the search element with the first element in the list.
Step 3 - If both are matched, then display "Given element is found!!!" and terminate the function
Step 4 - If both are not matched, then compare search element with the next element in the list. Step
5 - Repeat steps 3 and 4 until search element is compared with last element in the list.
Step 6 - If last element in the list also doesn't match, then display "Element is not found!!!" and
terminate the function.
Example:
Consider the following list of elements and the element to be searched...
BINARY SEARCH:
• Binary search is the search technique which works efficiently on the sorted lists. Hence, in order to
search an element into some list by using binary search technique, we must ensure that the list is
sorted.
• Binary search follows divide and conquer approach in which, the list is divided into two halves and
the item is compared with the middle element of the list. If the match is found then, the location of
middle element is returned otherwise, we search into either of the halves depending upon the result
produced through the match.
Algorithm:
Step 1 - Read the search element from the user.
Step 2 - Find the middle element in the sorted list.
Step 3 - Compare the search element with the middle element in the sorted list.
Step 4 - If both are matched, then display "Given element is found!!!" and terminate the function.
Step 5 - If both are not matched, then check whether the search element is smaller or larger than the
middle element.
Step 6 - If the search element is smaller than middle element, repeat steps 2, 3, 4 and 5 for the left
sublist of the middle element.
Step 7 - If the search element is larger than middle element, repeat steps 2, 3, 4 and 5 for the right
sublist of the middle element.
Step 8 - Repeat the same process until we find the search element in the list or until sublist contains
only one element.
Step 9 - If that element also doesn't match with the search element, then display "Element is not found
in the list!!!" and terminate the function.
Example:
Example 2:
FIBONACCI SEARCH:
Fibonacci search is an efficient search algorithm based on divide and conquer principle that can find
an element in the given sorted array with the help of Fibonacci series in O(log N) time complexity.
This is based on Fibonacci series which is an infinite sequence of numbers denoting a pattern which is
captured by the following equation:
F(n)=n if n<=1
F(n)=F(n-1)+F(n-2) if n>1
o where F(i) is the ith number of the Fibonacci series where F(0) and F(1) are defined as 0 and 1
respectively.
The first few Fibonacci numbers are: 0,1,1,2,3,5,8,13....
F(0) = 0
F(1) = 1
F(2) = F(1) + F(0) = 1 + 0 = 1 F(3) = F(2) +
F(1) = 1 + 1 = 2
F(4) = F(3) + F(2) = 1 + 2 = 3 and so continues the series
Other searches like binary search also work for the similar principle on splitting the search space to a
smaller space but what makes Fibonacci search different is that it divides the array in unequal parts
and operations involved in this search are addition and subtraction these arithmetic operations
takes place simple and hence reducing the work load of the computing machine.
Algorithm:
Let the length of given array be n [0...n-1] and the element to be searched be x.
Then we use the following steps to find the element with minimum steps:
1. Find the smallest Fibonacci number greater than or equal to n. Let this number be f(M)
Let the two Fibonacci numbers preceding it be f(M-1) and f(M-2). F(M) =
F(Size of array)
F(M-1) = F(M) - 1
F(M-2) = F(M-1) -1
i (index) = min (offset + F(M-2) , n-1) //Offset = -1
2. While the array has elements to be checked:
-> Compare x with the last element of the range covered by f(M-2)
-> If x matches, return index value
-> Else if x is less than the element, move the three Fibonacci variables two Fibonacci down,
Indicating removal of approximately two-third of the unsearched array from rear end. Not Reset offset
to index
-> Else x is greater than the element, move the three Fibonacci variables one Fibonacci down. Reset
offset to index. Indicating removal of approximately one-third of the unsearched array from front end.
3. Since there might be a single element remaining for comparison, check if F(M-1) is '1'. If Yes,
compare x with that remaining element. If match, return index value.
SORTINGS:
Categories of Sorting:
The sorting can be divided into two categories. These are:
Internal Sorting
External Sorting
Internal Sorting: When all the data that is to be sorted can be accommodated at a time in the main
memory (Usually RAM). Internal sortings has five different classifications: insertion, selection,
exchanging, merging, and distribution sort
External Sorting: When all the data that is to be sorted can’t be accommodated in the memory
(Usually RAM) at the same time and some have to be kept in auxiliary memory such as hard disk,
floppy disk, magnetic tapes etc.
Ex: Natural, Balanced, and Polyphase.
INSERTION SORT:
In Insertion sort the list can be divided into two parts, one is sorted list and other is unsorted list. In
each pass the first element of unsorted list is transfers to sorted list by inserting it in appropriate
position or proper place.
The similarity can be understood from the style
we arrange a deck of cards. This sort works on
the principle of inserting an element at a
particular position, hence the name Insertion
Sort.
Following are the steps involved in insertion sort:
1. We start by taking the second element of the given array, i.e. element at index 1, the key. The
key element here is the new card that we need to add to our existing sorted set of cards
2. We compare the key element with the element(s) before it, in this case, element at index 0:
o If the key element is less than the first element, we insert the key element before the first element.
o If the key element is greater than the first element, then we insert it after the first element.
3. Then, we make the third element of the array as key and will compare it with elements to it's left
and insert it at the proper position.
4. And we go on repeating this, until the array is sorted.
Example 1:
Example 2:
SELECTION SORT:
Given a list of data to be sorted, we simply select the smallest item and place it in a sorted list. These
steps are then repeated until we have sorted all of the data.
In first step, the smallest element is search in the list, once the smallest element is found, it is
exchanged with the element in the first position.
Now the list is divided into two parts. One is
sorted list other is unsorted list. Find out the
smallest element in the unsorted list and it is
exchange with the starting position of
unsorted list, after that it will added in to
sorted list.
This process is repeated until all the elements are
sorted. Ex: asked to sort a list on paper.
Algorithm:
SELECTION SORT(ARR, N)
Step 1: Repeat Steps 2 and 3 for K = 1 to N-1 Step 2: CALL
SMALLEST(ARR, K, N, Loc)
Step 3: SWAP A[K] with ARR[Loc] Step 4: EXIT
Algorithm for finding minimum element in the list.
SMALLEST (ARR, K, N, Loc)
Step 1: [INITIALIZE] SET Min = ARR[K] Step 2:
[INITIALIZE] SET Loc = K
Step 3: Repeat for J = K+1 to N
IF Min > ARR[J]
SET Min = ARR[J]
SET Loc = J [END OF IF]
[END OF LOOP]
Step 4: RETURN Loc
Example 1:
Example 2: Consider the elements 23,78,45,88,32,56
Time Complexity:
Number of elements in an array is ‘N’ Number of
passes required to sort is ‘N-1’
Number of comparisons in each pass is 1st pass N-1, 2nd Pass N-2 … Time required
for complete sorting is:
T(n) <= (N-1)*(N-1) T(n) <= (N-1)2
Finally, The time complexity is O(n2).
BUBBLE SORT:
Example 1:
We take an unsorted array for our example.
Bubble sort starts with very first two elements, comparing them to check which one is greater.
In this case, value 33 is greater than 14, so it is already in sorted locations. Next, we compare 33
with 27. We find that 27 is smaller than 33 and these two values must be swapped.
Next we compare 33 and 35. We find that both are in already sorted positions.
Then we move to the next two values, 35 and 10. We know then that 10 is smaller 35.
We swap these values. We find that we have reached the end of the array. After one iteration, the
array should look like this −
To be defined, we are now showing how an array should look like after each iteration. After the
second iteration, it should look like this
Notice that after each iteration, at least one value moves at the end.
And when there's no swap required, bubble sorts learns that an array is completely sorted.
Example 2:
Algorithm:
BUBBLE SORT(ARR, N)
Step 1: Read the array elements Step
2: i:=0;
Step 3: Repeat step 4 and step 5 until i<n Step
4: j:=0;
Step 5: Repeat step 6 until j<(n-1)-i Step 6:
if A[j] > A[j+1]
Swap(A[j],A[j+1])
End if
End loop 5
End loop 3
Step 7: EXIT
Time Complexity:
Number of elements in an array is ‘N’ Number of
passes required to sort is ‘N-1’
Number of comparisons in each pass is 1st pass N-1, 2nd Pass N-2 … Time required
for complete sorting is:
T(n) <= (N-1)*(N-1) T(n) <= (N-1)2
Finally, The time complexity is O(n2).
QUICK SORT:
Quick sort follows Divide and Conquer algorithm. It is dividing array in to smaller parts based on
partitioning and performing the sort operations on those divided smaller parts. Hence, it works well
for large datasets.
So, here are the steps how Quick sort works in simple words.
1. First select an element which is to be called as pivot element.
2. Next, compare all array elements with the selected pivot element and arrange them in such a way
that, elements less than the pivot element are to its left and greater than pivot is to it's right.
3. Finally, perform the same operations on left and right side elements to the pivot element.
How does Quick Sort Partitioning Work
1. First find the "pivot" element in the array.
2. Start the left pointer at first element of the array.
3. Start the right pointer at last element of the array.
4. Compare the element pointing with left pointer and if it is less than the pivot element, then move
the left pointer to the right (add 1 to the left index). Continue this until left side element is greater
than or equal to the pivot element.
5. Compare the element pointing with right pointer and if it is greater than the pivot element, then
move the right pointer to the left (subtract 1 to the right index). Continue this until right side
element is less than or equal to the pivot element.
6. Check if left pointer is less than or equal to right pointer, then swap the elements in locations of
these pointers.
7. Check if index of left pointer is greater than the index of the right pointer, then swap pivot element
with right pointer.
Example:
Algorithm:
quickSort(array, lb, ub)
{
if(lb< ub)
{
pivotIndex = partition(arr, lb, ub);
quickSort(arr, lb, pIndex - 1);
quickSort(arr, pivotIndex+1, ub);
}
}
RADIX SORT:
Radix sort is a linear sorting algorithm for integers and uses the concept of sorting names in
alphabetical order. When we have a list of sorted names, the radix is 26 (or 26 buckets) because
there are 26 letters in the English alphabet. So radix sort is also known as bucket sort.
Observe that words are first sorted according to the first letter of the name. That is, 26 classes are
used to arrange the names, where the first class stores the names that begin with A, the second class
contains the names with B, and so on.
During the second pass, names are grouped according to the second letter. After the second pass,
names are sorted on the first two letters. This process is continued till the nth pass, where n is the
length of the name with maximum number of letters.
When radix sort is used on integers, sorting is done on each of the digits in the number. The sorting
procedure proceeds by sorting the least significant (LSD) to the most significant (MSD) digit. While
sorting the numbers, we have ten buckets, each for one digit (0, 1, 2, …, 9) and the number of passes
will depend on the length of the number having maximum number of digits.
ample 1: Sort the numbers given below using radix sort. 345, 654,
924, 123, 567, 472, 555, 808, 911
In the first pass, the numbers are sorted according to the digit at ones place.
After this pass, the numbers are collected bucket by bucket. In the second pass, the numbers are
sorted according to the digit at the tens place.
In the third pass, the numbers are sorted according to the digit at the hundreds place.
The numbers are collected bucket by bucket. After the third pass, the list can be given as final
sorted list. 123, 345, 472, 555, 567, 654, 808, 911, 924.
Algorithm:
1. Let A be a linear array of n elements A[1], A[2], A[3]......................A[n]. Digit is the total number of digit in
the largest element in array A.
2. Input n number of elements in an array A.
3. Find the total number of digits in the largest element in the array.
4. Initialize i=1 and repeat the steps 4 and 5 until( i<=Digit).
5. Initialize the bucket j=0 and repeat the steps 5until (j<n).
6. Compare the ith position of each element of the array with bucket number and place it in the
corresponding bucket.
7. Read the elements (S) of the bucket from 0th bucket to 9th bucket and from the first position to the higher
one to generate new array A.
8. Display the sorted array A.
9. Exit.
MERGE SORT:
Merge sort is one of the most efficient sorting algorithms. It works on the principle of Divide and
Conquer. Merge sort repeatedly breaks down a list into several sublists until each sublist consists of a
single element and merging those sublists in a manner that results into a sorted list.
Implementation Recursive Merge Sort:
The merge sort starts at the Top and proceeds downwards, “split the array into two, make a
recursive call, and merge the results.”, until one gets to the bottom of the array-tree.
Example: Let us consider an example to understand the approach better.
1. Divide the unsorted list into n sub-lists based on mid value, each array consisting 1 element
2. Repeatedly merge sub-lists to produce newly sorted sub-lists until there is only 1 sub-list
remaining. This will be the sorted list
Recursive Mere Sort Example:
Example 2:
MergeSort Algoritm:
MergeSort(A, lb, ub )
{
If lb<ub
{
mid = floor(lb+ub)/2; mergeSort(A, lb, mid)
mergeSort(A, mid+1, ub) merge(A, lb, ub ,
mid)
}
}
Two- Way Merge Sort:
Merge Algorithm:
Step 1: set i,j,k=0
Step 2: if A[i]<B[j] then
copy A[i] to C[k] and increment i and k
else
copy B[j] to C[k] and increment j and k
Step 3: copy remaining elements of either A or B into Array C.
Time Complexities All the Searching & Sorting Techniques:
www.Jntufastupdates.c 1
om
UNIT-II
www.Jntufastupdates.c 2
om
www.Jntufastupdates.c 3
om
www.Jntufastupdates.c 4
om
www.Jntufastupdates.c 5
om
www.Jntufastupdates.c 6
om
www.Jntufastupdates.c 7
om
www.Jntufastupdates.c 8
om
www.Jntufastupdates.c 9
om
www.Jntufastupdates.c 10
om
www.Jntufastupdates.c 11
om
www.Jntufastupdates.c 12
om
www.Jntufastupdates.c 13
om
www.Jntufastupdates.c 14
om
www.Jntufastupdates.c 15
om
www.Jntufastupdates.c 16
om
www.Jntufastupdates.c 17
om
www.Jntufastupdates.c 18
om
www.Jntufastupdates.c 19
om
www.Jntufastupdates.c 20
om
www.Jntufastupdates.c 21
om
www.Jntufastupdates.c 22
om
www.Jntufastupdates.c 23
om
www.Jntufastupdates.c 24
om
www.Jntufastupdates.c 25
om
Unit – III
Syllabus:
• Queues: Introduction to Queues, Representation of Queues-using Arrays and using Linked list,
Implementation of Queues-using Arrays and using Linked list, Application of Queues-Circular Queues,
Deques, Priority Queues, Multiple Queues.
• Stacks: Introduction to Stacks, Array Representation of Stacks, Operations on Stacks, Linked list
Representation of Stacks, Operations on Linked Stack, Applications-Reversing list, Factorial Calculation, Infix
to Postfix Conversion, Evaluating Postfix Expressions.
QUEUE:
● The deletion or insertion of elements can take place only at the front or rear end called dequeue
and enqueue respectively. The first element that gets added into the queue is the first one to get
removed from the queue. Hence the queue is referred to as First-In- First-Out list (FIFO).
REPRESENTATION OF QUEUEs:
www.Jntufastupdates.c 26
om
for 50 elements in the queue and it hardly uses 20–25 locations, then half of the space will be wasted.
LINKED LISTs:
In a linked queue, every element has two parts, one that stores the data and another that stores
the address of the next element.
The START pointer of the linked list is used as FRONT. Here, we will also use another pointer
called REAR, which will store the address of the last element in the queue. All insertions will be
done at the rear end and all the deletions will be done at the front end.
If FRONT = REAR = NULL, then it indicates that the queue is empty.
IMPLEMENTATION OF QUEUEs:
Using Arrays:
Algorithm for ENQUEUE operation
1. Check whether queue is FULL. (rear >= SIZE-1)
2. If it is FULL, then display an error message "Queue is FULL!!! Insertion is not possible!!!" and
terminate the function.
3. If it is NOT FULL, then increment rear value by one (rear++) and set queue[rear]
= value.
Implementation:
www.Jntufastupdates.c 27
om
Let us consider a queue, which can hold maximum
of five elements.
Initially the queue is empty. An element can be added to
the queue only at the rear end of the queue.
Before adding an element in the queue, it is checked
whether queue is full. If the queue is full, then addition
cannot take place. Otherwise, the element is added to the
end of the list at the
rear end. If
we are inserting first element into the queue then change front to 0 (Zero).
Now, delete an element 1. The
element deleted is the element at the front of the queue. So the status of the queue is:
When the last element delete 5.
The element deleted at the front of the queue. So the status of the queue is empty. So change the
values of front and rear to -1 (front=rear= -1)
The dequeue operation deletes the element from the front of the queue.
Before deleting and element, it is checked if the queue is empty. If not the element pointed by
front is deleted from the queue and front is now made to point to the next element in the queue.
Drawback: If we implement the queue using an array, we need to specify the array size at the
beginning (at compile time). We can't change the size of an array at runtime. So, the queue will
only work for a fixed number of elements.
www.Jntufastupdates.c 28
om
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. Initially
Enqueue function: Enqueue function will add the element at the end of the linked list.
2. If front == NULL, make both front and rear points to the new node.
3. Otherwise, add the new node in rear->next (end of the list) and make the new
node as the rear node. i.e. rear = new node
Dequeue function: Dequeue function will remove the first element from the queue.
3. Otherwise, Make the front node points to the next node. i.e front = front->next; if front
Example: Enqueue()
www.Jntufastupdates.c 29
om
Dequeue()
TYPES OF QUEUES:
A queue data structure can be classified into the following types:
1. Circular Queue 2. Deque 3. Priority Queue 4. Multiple Queue
CIRCULAR QUEUEs:
In a Linear queue, once the queue is completely full, it's not possible to insert any more elements.
When we dequeue any element to remove it from the queue, we are actually moving the front of
the queue forward, but rear is still pointing to the last element of the queue, we cannot insert
new elements.
Circular Queue is also a linear data structure, which follows the principle of FIFO(First In First Out),
but instead of ending the queue at the last position, it again starts from the first position after the
last, hence making the queue behave like a circular data structure.
Operations on Circular Queue: The following are the operations that can be performed
o enQueue(value): This function is used to insert the new value in the Queue. The new element is
always inserted from the rear end.
o deQueue(): This function deletes an element from the Queue. The deletion in a Queue always
takes place from the front end.
Queue is full:
o When front ==0 && rear = max-1, which means that front is at the first position of the Queue and
rear is at the last position of the Queue.
o front== rear + 1;
www.Jntufastupdates.c 30
om
Dequeue Operation: The steps of dequeue operation are given below:
o First, we check whether the Queue is empty or not. If the queue is empty, we cannot perform
the dequeue operation.
o When the element is deleted, the value of front gets decremented by 1.
o If there is only one element left which is to be deleted, then the front and rear are reset -1.
Let's understand the enqueue and dequeue operation through the diagrammatic
representation.
Applications of Queue:
1. Queues are widely used as waiting lists for a single shared resource like printer, disk, CPU.
2. Queues are used to transfer data asynchronously between two processes
3. Queues are used as buffers on MP3 players and portable CD players, iPod playlist.
4. Queues are used in Playlist for jukebox to add songs to the end, play from the front.
5. Queues are used in operating system for handling interrupts. The interrupts are handled in the same
order as they arrive i.e First come first served.
www.Jntufastupdates.c 31
om
DEQUE:
Deque or Double Ended Queue is a type of
queue in which insertion and removal of
elements can be performed from either from
the front or rear. Thus, it does not follow FIFO
rule (First In First Out).
Types of Deque:
1. Input Restricted Deque: In this deque, input is restricted at a single end but allows
deletion at both the ends.
2. Output Restricted Deque: In this deque, output is restricted at a single end but allows
insertion at both the ends.
Operations on a Deque
Initially take an array (deque) of size n. and Set two pointers at the first position and set front = -1
and rear = -1.
1. Insert at the Front: This operation adds an element at the front.
Check the position of front, If front < 1, we can’t add elements in the front end. Otherwise
decrement the front and at front location we can insert the element.
2. Insert at the Rear: This operation adds an element to the rear.
Check if the array is full. Then the queue is overflow. Otherwise, reinitialize rear = 0 & front=0 for
the first insertion, Else, increase rear by 1.and at rear location we can insert the element.
3. Delete from the Front: The operation deletes an element from the front.
Check If the deque is empty (i.e. front = -1), deletion cannot be performed (underflow condition). If
the deque has only one element (i.e. front = rear), set front = -1 and rear = -1. Else, front = front +
1.
4. Delete from the Rear: This operation deletes an element from the rear.
If the deque is empty (i.e. front = -1), deletion cannot be performed (underflow condition). If the
deque has only one element (i.e. front = rear), set front = -1 and rear = -1. Else, rear = rear - 1.
www.Jntufastupdates.c 32
om
Priority Queue:-
A priority queue is a data structure in which each element is assigned a priority. The priority of the
element will be used to determine the order in which the elements will be processed.
The general rules of processing the elements of a priority queue are
o An element with higher priority is processed before an element with a lower priority.
o Two elements with the same priority are processed on a first-come-first-served (FCFS) basis.
Array Representation of a Priority Queue:
When arrays are used to implement a priority queue, then a separate queue for each priority
number is maintained. Each of these queues will be implemented using circular arrays or circular
queues. Every individual queue will have its own FRONT and REAR pointers.
We use a two-dimensional array for this purpose where each queue will be allocated the same
amount of space.
FRONT[P] and REAR[P] contain the front and rear values of row P, where P is the priority number.
Insertion:
To insert a new element with priority P in the priority queue, add the element at the rear end of row
P, where P is the row number as well as the priority number of that element.
For example, if we have to insert an element X with priority number 2, then the priority queue will
be given as shown in Fig.
www.Jntufastupdates.c 33
om
Deletion:
To delete an element, we find the first nonempty queue and then process the front element of the
first non-empty queue.
In our priority queue, the first non-empty queue is the one with priority number 6 and the front
element is K, so K will be deleted and processed first.
Multiple Queues:-
When we implement a queue using an array, the size of the array must be known in advance. If the
queue is allocated less space, then frequent overflow conditions will be encountered. To deal with
this problem, the code will have to be modified to reallocate more space for the array.
In case we allocate a large amount of space for the queue, it will result in sheer wastage of the
memory. So a better solution to deal with this problem is to have multiple queues or to have more
than one queue in the same array of sufficient size.
An array Queue[n] is used to represent two queues, Queue A and Queue B. The value of n is such
that the combined size of both the queues will never exceed n. While operating on these queues, it
is important to note one thing—queue A will grow from left to right, whereas queue B will grow
from right to left at the same time.
Example:
In the above example the array consists two queues like QA and QB. For QA there are pointers
like fA(front of QA) and rA(rear of A). similarly for QB are fB & rB.
Initially for QA, the pointer values of fA=rA= -1. For QB, the pointer values are fB=rB=SIZE.
Because initially QA and QB are empty.
For the first insertion in QA, the values of fA=rA=0. Similarly for QB, the values are fB=rB=SIZE-
1.
From the second insertion onwards we can increment only the rear pointer rA for QA and
decrement the rear rB for QB.
Delete the elements from queue only at front end. In QA, the elements can delete from fA, if you
delete the element then increment fA. In QB, the elements can delete from fB, if you delete the
element then decrement fB.
When the condition rA=rB-1 or rA+1=rB meets then the entire queue is full. If you try to insert the
element in either of queues it says that QUEUE is OVERFLOW.
www.Jntufastupdates.c 34
om
Stack:-
● Stack is also called as Last-In-First-Out (LIFO) list which means that the
last element that is inserted will be the first element to be removed
from the stack.
● When a stack is completely full, it is said to be Stack is Overflow and if stack is completely empty, it
is said to be Stack is Underflow.
Every stack has a variable called TOP associated with it, which is used to pointing the topmost
element of the stack. It is this position where the element will be inserted to or deleted from.
There is another variable called MAX, which is used to store the maximum number of elements that
the stack can hold.
If TOP = NULL, then it indicates that the stack is empty and if TOP = MAX–1, then the stack is full.
www.Jntufastupdates.c 35
om
Algorithm for POP operation
The drawback in that the array must be declared to have some fixed size. In case the stack is a very
small one or its maximum size is known in advance
In a linked stack, every node has two parts, one that stores data and another that stores the
address of the next node. The START pointer of the linked list is used as TOP.
All insertions and deletions are done at the TOP (similar to insertion at beginning).
www.Jntufastupdates.c 36
om
If TOP = NULL, then it indicates that the stack is empty.
The linked representation of a stack is
PUSH function: PUSH function will add the element at the beginning of the linked list.
1. Declare a new node and allocate memory for it.
2. If TOP == NULL, make TOP points to the new node.
3. Otherwise, add the new node at TOP end and makes the next of new node is previous TOP.
POP function: POP function will remove the TOP element from the STACK.
1. Check whether the stack is empty or not
2. If it is the stack is empty (TOP == NULL), We can't POP the element.
3. Otherwise, Make the TOP node points to the next node. i.e TOP = TOP->next; Free the
TOP node's memory.
www.Jntufastupdates.c 37
om
Algorithms:
Applications of Stacks
Reversing list:
A list of numbers or string can be reversed by using the stack, perform the following steps
1. Reading the elements from the array and pushed into the stack.
2. Pop the elements and again stored into the array starting from first index
Algorithm: Example:
Factorial Calculation:
To find the solution of larger problem, a general method is reduce the larger problem into one or
more sub problems. This process will continuous until the sub problem is finding the solution.
Finally using all the sub problems solutions we will find the solution for the larger problem.
www.Jntufastupdates.c 38
om
A Recursion is defined as a function that calls itself.
To understand recursion, let us take an example of calculating factorial of a number.
To calculate n!, we multiply the number with factorial of the number that is 1 less than that
number. n! = n*(n-1)*(n-2)* ... *2*1
In other words, n! = n * (n–1)!
Let us say we need to find the value of 5!
5! = 5 * 4 * 3 * 2 * 1 = 120
This can be written as 5! = 5 * 4!,
where 4!= 4 * 3!
Therefore, 5! = 5 * 4 * 3!
Similarly, 5! = 5 * 4 * 3 * 2!
Expanding further 5! = 5 * 4 * 3 * 2 * 1!
We know, 1! = 1
Now if you look at the problem carefully, you can see that we can write a recursive function to
calculate the factorial of a number. Every recursive function must have a base case and a recursive
case. For the factorial function,
Base case is when n = 1, because if n = 1, the result will be 1 as 1! = 1.
Recursive case of the factorial function will call itself but with a smaller value of n, this case
can be given as factorial(n) = n × factorial (n–1)
Evaluation of Expressions:-
Prefix: An arithmetic expression in which we fix (place) the arithmetic operator before (pre) its two
operands. The prefix notation is called as polish notation. Example: + A B
Infix: An arithmetic expression in which we fix (place) the arithmetic operator in between the two
operands. Example: A + B
Postfix: An arithmetic expression in which we fix (place) the arithmetic operator after (post) its two operands.
The postfix notation is called as suffix notation OR reverse polish notation.
Example: A B +
Operator Precedence: When an expression consist different level of operators we follow it. We consider
five binary operations: +, -, *, / and ^ (exponentiation). For these binary operations, the following in the
order of precedence (highest to lowest): ^ , * , /, +, -
www.Jntufastupdates.c 39
om
Operator Associativity: When an expression consist more than one same level precedence operators we
follow it.
Basically we have Left to Right associativity and Right to Left Associativity. Most of the operators are
follows Left to Right but some of the operators are follow Right to left Associativity like Unary (+/-), +
+/-- , Logical negation (!), Pointer and address (*,&), Conditional Operators and Assignment
operators(=,+=,-=,*=,/=,%=).
Example: x=a/b–c+d*e–a*c
= ((4 / 2) – 2) + (3 * 3) – (4 * 2) =0+9–8 =1
Postfix Expression is 5 3 + 8 2 - *
Symbol Stack Evaluation
Initially
Stack is empty
5
5
www.Jntufastupdates.c 40
om
Push(5)
www.Jntufastupdates.c 41
om
3
3 5
Push(3)
Value1=3 Value2=5
8
+ Result=5+3=8 Push(8)
Value1=pop()
Value2=pop() Result=Value2+Value1 Push(Result)
8
8
Push(8) 8
2
2 8
8
Push(2)
Value1=2 Value2=8
6 Result=8-2=6 Push(6)
- 8
Value1=pop() Value2=Pop() Result=Value2-Value1
Push(Result)
Value1=6 Value2=8
* Result=8*6=48
Value1=pop() Push(48)
48
Value2=Pop() Result=Value2*Value1 Push(Result)
www.Jntufastupdates.c 42
om
Conversion of INFIX the stack. If top of Stack has lower precedence over
to POSTFIX:
the scanned character then push the operator into
Procedure to convert
from infix expression the stack else pop the element from the stack and add
to postfix expression is it to postfix string and push the scanned character to
as follows.
stack.
1. Initialize an empty
stack
2. Push “(“onto Stack, Example: a * (b + c) *d)
and add “)” to the end
of Infix string.
3. Scan the Infix string T Stack Postfix
from left to right until o String
end of the infix k
e
i. If the scanned character is n
“(“, pushed into the
stack. (
a ( a
ii. If the scanned character
is “)”, pop the * ( * A
elements from the ( ( * ( A
stack up to b ( * ( Ab
encountering the + ( * ( + Ab
“(“, and add the c ( * ( + Abc
popped elements ) ( * abc+
to postfix string ( *
* abc+*
except ( *
d abc+*d
parentheses.
) abc+*d*
iii. If the scanned character is
an operand, add it to
the Postfix string.
iv. If the scanned character
is an Operator,
compare the
precedence of the
character with the
element on top of
UNIT-V
A graph is an abstract data structure that is used to implement the mathematical concept of
graphs. It is basically a collection of vertices (also called nodes) and edges that connect these
vertices. A graph is often viewed as a generalization of the tree structure, where instead of
having a purely parent-to-child relationship between tree nodes, any kind of complex
relationship can exist.
DEFINATION:
A graph G is defined as an ordered set (V, E), where V(G) represents the set of vertices and E(G)
represents the edges that connect these vertices.
We have two types of Graphs. Basically:
1. UNDIRECTED GRAPH
2. DIRECTED
GRAPH UNDIRECTED
GRAPH:
Shows a graph with V(G) = {A, B, C, D and E} and E(G) = {(A, B), (B, C), (A, D), (B, D),
(D,E), (C, E)}. Note that there are five vertices or nodes and six edges in the graph.
FIGURE 5.1
A graph can be directed or undirected. In an undirected graph, edges do not have any
direction associated with them. That is, if an edge is drawn between nodes A and B, then the
nodes can be traversed from A to B as well as from B to A. Figure 5.1 shows an undirected
graph because it does not give any information about the direction of the edges.
DIRECTED GRAPH:
A directed graph G, also known as a digraph, is a graph in which every edge has a direction
assigned to it. An edge of a directed graph is given as an ordered pair (u, v) of nodes in G.
For an edge (u, v),
The edge begins at u and terminates at v.
u is known as the origin or initial point of e. Correspondingly, v is known as the
destination or terminal point of e.
u is the predecessor of v. Correspondingly, v is the successor of u.
Nodes u and v are adjacent to each other.
FIGURE 5.2
Which shows a directed graph. In a directed graph, edges form an ordered pair. If there is an
edge from A to B, then there is a path from A to B but not from B to A. The edge (A, B) is
said to initiate from node A (also known as initial node) and terminate at node B (terminal
node).
2. REPRESENTATION OF GRAPHS
There are two common ways of storing graphs in the computer’s memory. They are:
Sequential representation by using an adjacency matrix.
Linked representation by using an adjacency list that stores the neighbours of a node
using a linked list.
Since an adjacency matrix contains only 0s and 1s, it is called a bit matrix or a Boolean
matrix. The entries in the matrix depend on the ordering of the nodes in G. Therefore, a
change in the order of nodes will result in a different adjacency matrix.
Figure 5.4 shows some graphs and their corresponding adjacency matrices.
means that there exists a path of length 1 from vi to vj. Now consider, A2, A3, and A4.
Any entry aij = 1 if aik = akj = 1. That is, if there is an edge (vi, vk) and (vk, vj), then
there is a path from vi to vj of length 2.
Br = A1 + A2 + A3 + ... + A r
An adjacency list is another way in which graphs can be represented in the computer’s
memory.
This structure consists of a list of all nodes in G.
Furthermore, every node is in turn linked to its own list that contains the names of all other
nodes that are adjacent to it.
The key advantages of using an adjacency list are:
It is easy to follow and clearly shows the adjacent nodes of a particular node.
It is often used for storing graphs that have a small-to-moderate number of edges. That is,
an adjacency list is preferred for representing sparse graphs in the computer’s memory;
otherwise, an adjacency matrix is a good choice.
Adding new nodes in G is easy and straightforward when G is represented using an
adjacency list. Adding new nodes in an adjacency matrix is a difficult task, as the size of the
matrix needs to be changed and existing nodes may have to be reordered.
FIGURE 5.7 Graph G and its adjacency list
For a directed graph, the sum of the lengths of all adjacency lists is equal to the number of
edges in G.
However, for an undirected graph, the sum of the lengths of all adjacency lists is equal to
twice the number of edges in G because an edge (u, v) means an edge from node u to v as
well as an edge from v to u.
Adjacency lists can also be modified to store weighted graphs.
Let us now see an adjacency list for an undirected graph as well as a weighted graph.
FIGURE 5.8 Adjacency list for an undirected graph and a weighted graph
PROGRAMMING EXAMPLE
Note If the graph in the above program had been a weighted graph, then the structure of the
node would have been:
typedef struct node
{
int
vertex
; int
weigh
t;
struct node *next;
};
3.GRAPH TRAVERSALS
There are two standard methods of graph traversal. These two methods are:
1. Breadth-first search
2. Depth-first search
1. Breadth-First Search Algorithm
Breadth-first search (BFS) is a graph search algorithm that begins at the root node and
explores all the neighbouring nodes. Then for each of those nearest nodes, the algorithm
explores their unexplored neighbour nodes, and so on, until it finds the goal.
ALGORITHM
Step 1: SET STATUS = 1 (ready
state) for each node in G
Step 2: Enqueue the starting node
A and set its STATUS = 2
(waiting state)
Step 3: Repeat Steps 4 and 5 until QUEUE is empty
Step 4: Dequeue a node N.
Process it and set its STATUS = 3
(processed state).
Step 5: Enqueue all the
neighbours of N that are in the
ready state
(whose STATUS = 1) and
set their STATUS = 2
(waiting
state) [END
OF LOOP]
Step 6: EXIT
(g)Dequeue a node by setting FRONT = FRONT + 1 and enqueue the neighbours of G. Also,
add G as the ORIG of its neighbours. Note that G has three neighbours F, H, and I.
FRONT = 6 QUEUE = A B C D E G F H I
REAR = 9 ORIG = \0 A A A B C E G
G
Since F has already been added to the queue, we will only add H and I. As I is our final
destination, we stop the execution of this algorithm as soon as it is encountered and added to
the QUEUE. Now, backtrack from I using ORIG to find the minimum path P. Thus, we have
P as A -> C -> G -> I.
Features of Breadth-First Search Algorithm
Space complexity:
The space complexity is therefore proportional to the number of nodes at the
deepest level of the graph.
Given a graph with branching factor b (number of children at each node) and depth
d, the asymptotic space complexity is the number of nodes at the deepest level O(bd).
The space complexity can also be expressed as O ( | E | + | V | ), where | E | is the
total number of edges in G and | V | is the number of nodes or vertices.
Time Complexity:
In the worst case, breadth-first search has to traverse through all paths to all
possible nodes, thus the time complexity of this algorithm asymptotically approaches O(bd).
However, the time complexity can also be expressed as O( | E | + | V | ), since
every vertex and every edge will be explored in the worst case.
Completeness:
Breadth-first search is said to be a complete algorithm because if there is a solution,
breadth-first search will find it regardless of the kind of graph. But in case of an infinite
graph where there is no possible solution, it will diverge.
Optimality:
Breadth-first search is optimal for a graph that has edges of equal length, since it
always returns the result with the fewest edges between the start node and the goal node.
we have weighted graphs that have costs associated with each edge, so the goal
next to the start does not have to be the cheapest goal available.
Applications of Breadth-First Search Algorithm
Breadth-first search can be used to solve many problems such as:
Finding all connected components in a graph G.
Finding all nodes within an individual connected component.
Finding the shortest path between two nodes, u and v, of an unweighted graph.
Finding the shortest path between two nodes, u and v, of a weighted graph.
Programming Example
2. Write a program to implement the breadth-first search
#define MAX 10
queue[++rear] = start;
visited[start] = 1;
while(rear !=
front)
{
start = queue[+
+front]; if(start ==
4) printf("5\t");
else
printf("%c \t",start +
i++)
{
if(adj[start][i] == 1 && visited[i] == 0)
queue[++rear] = i;
visited[i] = 1;
int main()
{
int visited[MAX] =
{0}; int adj[MAX]
[MAX], i, j;
printf("\n Enter the adjacency matrix:
"); for(i = 0; i < MAX; i++)
for(j = 0; j < MAX; j++)
scanf("%d", &adj[i][j]);
breadth_first_search(adj,visite
d,0); return 0;
}
Output
Enter the adjacency matrix:
01010
10110
01001
11001
00110
ABDCE
2. Depth First Algorithm
The depth-first search algorithm progresses by expanding the starting node of G and then
going deeper and deeper until the goal node is found, or until a node that has no children is
encountered.
When a dead-end is reached, the algorithm backtracks, returning to the most recent node that
has not been completely explored.
Algorithm
Step 1: SET STATUS = 1 (ready state) for each node
in G Step 2: Push the starting node A on the stack and
set
its STATUS = 2 (waiting state)
Step 3: Repeat Steps 4 and 5 until STACK is
empty Step 4: Pop the top node N. Process it
and set its
STATUS = 3 (processed state)
Step 5: Push on the stack all the neighbours of N that are
in the ready state (whose STATUS = 1) and set
their STATUS = 2 (waiting state)
[END OF
LOOP] Step 6: EXIT
FIGURE 5.10 Graph G And Its Adjacency List
Example:
Consider the graph G given in. The adjacency list of G is also given. Suppose we want to
print all the nodes that can be reached from the node H (including H itself). One alternative
is to use a depth-first search of G starting at node H. The procedure can be explained here.
Solution:
(a) Push H onto the stack.
STACK: H
(b)Pop and print the top element of the STACK, that is, H. Push all the neighbours of H
onto the stack that are in the ready state. The STACK now becomes
PRINT: H STACK: E, I
(c) Pop and print the top element of the STACK, that is, I. Push all the neighbours of I
onto the stack that are in the ready state. The STACK now becomes
PRINT: I STACK: E, F
(d)Pop and print the top element of the STACK, that is, F. Push all the neighbours of F
onto the stack that are in the ready state. (Note F has two neighbours, C and H. But only C
will be added, as H is not in the ready state.) The STACK now becomes
PRINT: F STACK: E, C
e) Pop and print the top element of the STACK, that is, C. Push all the neighbours of C
onto the stack that are in the ready state. The STACK now becomes
PRINT: C STACK: E, B, G
(f) Pop and print the top element of the STACK, that is, G. Push all the neighbours of G
onto the stack that are in the ready state. Since there are no neighbours of G that are in
the ready state,
no push operation is performed. The STACK now becomes PRINT:
G STACK: E, B
(g)Pop and print the top element of the STACK, that is, B. Push all the neighbours of B onto
the stack that are in the ready state. Since there are no neighbours of B that are in the
ready state,
no push operation is performed. The STACK now becomes PRINT:
B STACK: E
h) Pop and print the top element of the STACK, that is, E. Push all the neighbours of E
onto the stack that are in the ready state. Since there are no neighbours of E that are in the
ready state, no push operation is performed. The STACK now becomes empty.
PRINT: E STACK:
Since the STACK is now empty, the depth-first search of G starting at node H is complete
and the nodes which were printed are:
H, I, F, C, G, B, E
These are the nodes which are reachable from the node H.
Features of Depth-First Search
Algorithm Space complexity:
The space complexity of a depth-first search is lower than that of a breadth first search.
Time complexity:
The time complexity of a depth-first search is proportional to the number of vertices plus the
number of edges in the graphs that are traversed. The time complexity can be given as (O(|V|
+|E|)).
Completeness:
Depth-first search is said to be a complete algorithm. If there is a solution, depthfirst search
will find it regardless of the kind of graph. But in case of an infinite graph, where there is no
possible solution, it will diverge.
APPLICATIONS
MINIMUM SPANNING TREES:
A spanning tree of a connected, undirected graph G is a sub-graph of G which is a tree that
connects all the vertices together
A graph G can have many different spanning trees.
We can assign weights to each edge (which is a number that represents how unfavourable
the edge is), and use it to assign a weight to a spanning tree by calculating the sum of the
weights of the edges in that spanning tree.
A minimum spanning tree (MST) is defined as a spanning tree with weight less than or
equal to the weight of every other spanning tree. In other words, a minimum spanning
tree is a spanning tree that has weights associated with its edges, and the total weight of the
tree (the sum of the weights of its edges) is at a minimum.
Example: Consider an unweighted graph G given below (Fig. 5.11). From G, we can draw
many distinct spanning trees. Eight of them are given here. For an unweighted graph, every
spanning tree is a minimum spanning tree.
EXAMPLE: Consider a weighted graph G shown in Fig. 5.12. From G, we can draw three
distinct spanning trees. But only a single minimum spanning tree can be obtained, that is, the
one that has the minimum weight (cost) associated with it. Of all the spanning trees given in
Fig. 5.12, the one that is highlighted is called the minimum spanning tree, as it has the
lowest cost associated with it.
1. PRIM’S ALGORITHM
Prim’s algorithm is a greedy algorithm that is used to form a minimum spanning tree for a
connected weighted undirected graph.
In other words, the algorithm builds a tree that includes every vertex and a subset of the
edges in such a way that the total weight of all the edges in the tree is minimized.
For this, the algorithm maintains three sets of vertices which can be given as below:
Tree vertices Vertices that are a part of the minimum spanning tree T.
Fringe vertices Vertices that are currently not a part of T, but are adjacent to some tree
vertex.
Unseen vertices Vertices that are neither tree vertices nor fringe vertices fall under this
category.
ALGORITHM
Step 1: Select a starting vertex
Step 2: Repeat Steps 3 and 4 until there are fringe
vertices Step 3: Select an edge e connecting the tree
vertex and
fringe vertex that has minimum
weight Step 4: Add the selected edge and the
vertex to the
minimum spanning tree T
[END OF LOOP]
Step 5: EXIT
EXAMPLE: Construct a minimum spanning tree of the graph given in Fig. 5.13
FIGURE 5.13
Step 1: Choose a starting vertex A.
Step 2: Add the fringe vertices (that are adjacent to A). The edges connecting the vertex
and fringe vertices are shown with dotted lines.
Step 3: Select an edge connecting the tree vertex and the fringe vertex that has the minimum
weight and add the selected edge and the vertex to the minimum spanning tree T. Since the
edge connecting A and C has less weight, add C to the tree. Now C is not a fringe vertex
but a tree vertex.
Step 4: Add the fringe vertices (that are adjacent to C).
Step 5: Select an edge connecting the tree vertex and the fringe vertex that has the minimum
weight and add the selected edge and the vertex to the minimum spanning tree T. Since the
edge connecting C and B has less weight, add B to the tree. Now B is not a fringe vertex
but a tree vertex.
Step 6: Add the fringe vertices (that are adjacent to B).
Step 7: Select an edge connecting the tree vertex and the fringe vertex that has the
minimum weight and add the selected edge and the vertex to the minimum spanning tree
T. Since the edge connecting B and D has less weight, add D to the tree. Now D is not a
fringe vertex but a tree vertex.
Step 8: Note, now node E is not connected, so we will add it in the tree because a minimum
spanning tree is one in which all the n nodes are connected with n–1 edges that have
minimum weight. So, the minimum spanning tree can now be given as,
2. KRUSKAL’S ALGORITHM
Kruskal’s algorithm is used to find the minimum spanning tree for a connected weighted
graph.
The algorithm aims to find a subset of the edges that forms a tree that includes every
vertex. The total weight of all the edges in the tree is minimized.
However, if the graph is not connected, then it finds a minimum spanning forest. Note that
a forest is a collection of trees. Similarly, a minimum spanning forest is a collection of
minimum spanning trees.
Kruskal’s algorithm is an example of a greedy algorithm, as it makes the locally optimal
choice at each stage with the hope of finding the global optimum.
ALGORITHM
Step 1: Create a forest in such a way that each graph is a separate tree.
Step 2: Create a priority queue Q that contains all the edges of the
graph.
Step 3: Repeat Steps 4 and 5 while Q is NOT
EMPTY Step 4: Remove an edge from Q
Step 5: IF the edge obtained in Step 4 connects two different trees, then
Add it to the forest (for combining two trees into one tree).
ELSE
Discard the
edge Step 6: END
FIGURE 5.14
Step 1: Remove the edge (A, D) from Q and make the following changes:
F = {{A, D}, {B}, {C}, {E, F}} MST = {(A, D), (E, F)}
Q = {(C, E), (E, D), (C, D), (D, F),
(A, C), (A, B), (B, C)}
Step 3: Remove the edge (C, E) from Q and make the following changes:
Step 4: Remove the edge (E, D) from Q and make the following changes:
F = {A, B, C, D, E, F}
MST = {(A, D), (C, E), (E, F), (E,D), (A, B)}
Q = {(B, C)}
Step 9: The algorithm continues until Q is empty. Since the entire forest has become one
tree, all the remaining edges will simply be discarded. The resultant MS can be given as
shown below
F = {A, B, C, D, E, F}
MST = {(A, D), (C, E), (E, F), (E,D), (A, B)}
Q = {}
PROGRAMMING EXAMPLE:
5. Write a program which finds the cost of a minimum
spanning tree. #include<stdio.h>
#include<conio.h
> #define MAX
10
int adj[MAX][MAX], tree[MAX][MAX],
n; void readmatrix()
{
int i, j;
printf(“\n Enter the number of nodes in the Graph :
“); scanf(“%d”, &n);
printf(“\n Enter the adjacency matrix of the
Graph”); for (i = 1; i <= n; i++)
for (j = 1; j <= n; j+
+) scanf(“%d”,
&adj[i][j]);
}
int spanningtree(int src)
{
DE
PARTMENT OF INFORMATION TECHNOLOGY
int visited[MAX], d[MAX],
parent[MAX]; int i, j, k, min, u, v, cost;
for (i = 1; i <= n; i++)
{
d[i] = adj[src]
[i]; visited[i]
= 0; parent[i]
= src;
}
visited[src] = 1;
cost = 0;
k = 1;
for (i = 1; i < n; i++)
{
min = 9999;
for (j = 1; j <= n; j++)
{
if (visited[j]==0 && d[j] < min)
{
min =
d[j]; u =
j;
cost += d[u];
}
}
visited[u] = 1;
//cost = cost +
d[u]; tree[k][1] =
parent[u];
tree[k++][2] = u;
for (v = 1; v <= n; v++)
if (visited[v]==0 && (adj[u][v] < d[v]))
DE
PARTMENT OF INFORMATION TECHNOLOGY
{
d[v] = adj[u][v];
parent[v] = u;
}
}
return cost;
}
void display(int cost)
{
int i;
printf(“\n The Edges of the Mininum Spanning Tree
are”); for (i = 1; i < n; i++)
printf(“ %d %d \n”, tree[i][1], tree[i][2]);
printf(“\n The Total cost of the Minimum Spanning Tree is : %d”, cost);
}
main()
{
int source, treecost;
readmatrix();
printf(“\n Enter the Source :
“); scanf(“%d”, &source);
treecost =
spanningtree(source);
display(treecost);
return 0;
}
Output
Enter the number of nodes in the Graph : 4
Enter the adjacency matrix : 0 1 1 0
0001
0100
1010
Enter the source : 1
DE
PARTMENT OF INFORMATION TECHNOLOGY
The edges of the Minimum Spanning Tree are
1442
23
The total cost of the Minimum Spanning Tree is : 1
Dijkstra’s Algorithm
Dijkstra’s algorithm, given by a Dutch scientist Edsger Dijkstra in 1959, is used to find the
shortest path tree. This algorithm is widely used in network routing protocols, most notably
IS-IS and OSPF (Open Shortest Path First).
Given a graph G and a source node A, the algorithm is used to find the shortest path (one
having the lowest cost) between A (source node) and every other node. Moreover, Dijkstra’s
algorithm is also used for finding the costs of the shortest paths from a source node to a
destination node.
For example, if we draw a graph in which nodes represent the cities and weighted edges
represent the driving distances between pairs of cities connected by a direct road, then
Dijkstra’s algorithm when applied gives the shortest route between one city and all other
cities.
ALGORITHM
Dijkstra’s algorithm is used to find the length of an optimal path between two nodes in a
graph.
The term optimal can mean anything, shortest, cheapest, or fastest.
If we start the algorithm with an initial node, then the distance of a node Y can be given as
the distance from the initial node to that node.
Dijkstra’s algorithm labels every node in the graph where the labels represent the
distance (cost) from the source node to that node.
There are two kinds of labels: temporary and permanent.
Temporary labels are assigned to nodes that have not been reached, while permanent labels
are given to nodes that have been reached and their distance (cost) to the source node is
known. A node must be a permanent label or a temporary label, but not both.
The execution of this algorithm will produce either of the following two results:
1. If the destination node is labelled, then the label will in turn represent the distance
from the source node to the destination node.
2. If the destination node is not labelled, then there is no path from the source to the
destination node.
EXAMPLE:
Consider the graph G given in Fig. 5.14. Taking D as the initial node, execute the Dijkstra’s
algorithm on it.
FIGURE 5.14
PROGRAMMING EXAMPLE
clrscr();
printf("\n The adjacency matrix is : ");
display(adj, n);
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
if(adj[i][j] == 0)
P[i][j] = 0;
else
P[i][j] = 1;
}
}
for(k=0; k<n;k++)
{
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
P[i][j] = P[i][j] | ( P[i][k] & P[k][j]);
}
DE
PARTMENT OF INFORMATION TECHNOLOGY
}
printf("\n The Path Matrix is
:"); display (P, n);
getch(); return 0;
}
void read(int mat[5][5], int n)
{
int i, j;
for(i=0;i<n;i+
+)
{
for(j=0;j<n;j++)
{
printf("\n mat[%d][%d] = ", i, j);
scanf("%d", &mat[i][j]);
}
}
}
void display(int mat[5][5], int n)
{
int i, j;
for(i=0;i<n;i+
+) printf("\n");
for(j=0;j<n;j+
+)
printf("%d\t", mat[i][j]);
}
}
Output
The adjacency
matrix is 0 1 1 0
0011
0001
DE
PARTMENT OF INFORMATION TECHNOLOGY
1100
Graphs 417
The Path
Matrix is 1 1 1
1
1111
1111
1111
Transitive Closure of a Directed Graph
Definition
For a directed graph G = (V,E), where V is the set of vertices and E is the set of edges, the
transitive closure of G is a graph G* = (V,E*). In G*, for every vertex pair v, w in V there is
an edge (v, w) in E* if and only if there is a valid path from v to w in G.
ALGORITHM
Transitive_Closure(A, t, n)
DE
PARTMENT OF INFORMATION TECHNOLOGY
Step 1: SET i=1, j=1, k=1
Step 2: Repeat Steps 3 and 4 while
i<=n Step 3: Repeat Step 4 while
j<=n
Step 4: IF (A[i][j] = 1)
SET t[i][j] = 1
ELSE
SET t[i][j] =
INCREMENT j [END
OF LOOP]
INCREMENT i [END
OF LOOP]
Step 5: Repeat Steps 6 to 11 while k<=n
Step 6: Repeat Steps 7 to 1 while i<=n
Step 7: Repeat Steps 8 and 9 while
j<=n Step 8: SET t[i,j] = t[i][j] V (t[i]
[k] t[k][j])
Step 9: INCREMENT j
[END OF
LOOP] Step 10 :
INCREMENT i
[END OF LOOP]
Step 11: INCREMENT k
[END OF LOOP]
Step 12: END