Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
27 views

Dsa Course File

Uploaded by

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

Dsa Course File

Uploaded by

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

A Course File

On

DATA STRUCTURES AND ALGORITHMS

(II B. Tech I– Semester)

Submitted to

DEPARTMENT OF COMPUTER SCIENCE& ENGINEERING


(ET)
By

MRS. APARNA GULLAPELLY


(Dept. of ET)

HYDERABAD INSTITUTE OF TECHNOLOGY


AND MANAGEMENT
Gowdavalli (V), Medchal Mandal, Hyderabad – 501 401
Hyderabad Institute of Technology and Management

CONTENTS

S. No. Particulars Page No.

1 Syllabus 3-5

Lesson Plan
a) Schedule as per template
2 b) Course outcomes 6-11
c) CO-PO mapping
d) Course Projects (PBL)
a) Notes
3 12-155
b) Question bank

4 Previous Question bank 156-159

5 Model Question bank 160-161

2
Hyderabad Institute of Technology and Management

Syllabus

B.Tech II Year–I Sem L T P C


Subject Code: 22PC3CD01 3 1 2 5

Data Structures and Algorithms


Prerequisite: Basic mathematical, analytical and logical capability, problem solving through C.
Course Objectives:
• Introduce Analysis of Algorithm in terms of space and time complexity.
• Exploring basic data structures such as stacks and queues.
• Introduces a variety of data structures such as hash tables, search trees, tries, heaps,
graphs.
• Introduces sorting and pattern matching algorithms.

Module I
Introduction: Basics of Data Structures, Abstract data types, Dynamic aspects of operations
on data, Characteristics of data structures, Creation and manipulation of data structures,
Operations on data structures.

Introduction to Algorithms: asymptotic notations divide & conquer recursion, analyzing


recursive algorithms.

Programs:

1. Asymptotic notations to calculate the running time complexity of any algorithm. Ο


Notation (Big-O Notation), Ω Notation (Big-Omega Notation), θ Notation (Theta
Notation)
2. Calculate complexity analysis of control structures
3. Calculate complexity analysis of any recursive algorithm

Module II
Linked lists: Types of linked lists – singly, doubly and circularly linked lists, operations on
linked lists.

Stacks: Implementation of stacks– array and linked list, operations on stacks, Applications of
Stacks, Notations – infix, prefix and postfix, Conversion and evaluation of arithmetic
expressions using Stacks.
Queues: Implementation of queues– array and linked list, operations on queues, Types of
queues – queue, double ended queue and priority queue.

Programs:
1. Write a Program to Implement Stack Operations using Dynamic Memory Allocation.
2. Write a program to convert expressions infix to postfix using stack.
3. Write a program to evaluate arithmetic expressions using stack

3
Hyderabad Institute of Technology and Management

4. Write a program that uses functions to perform the following operations on Singly
linked list.
i) Creation ii) Insertion iii) Deletion iv) Traversal
5. Write a program that uses functions to perform the following operations on
Circular linked list.
i) Creation ii) Insertion iii) Deletion iv) Traversal
6. Write a program that implement Queue (its operations) using Arrays.
7. Write a program that implement stack (its operations) using Pointers

Module III
Dictionaries: Linear list representation, skip list representation, operations - insertion,
deletion and searching.

Hash Table Representation: hash functions, collision resolution-separate chaining, open


addressing- linear probing, quadratic probing, double hashing, rehashing, extendible
hashing.

Programs:
1. Write a program to implement dictionary linear list representation and its operations
2. Write a Program to Implement Hash Tables with Quadratic Probing
3. Write a Program to Implement Hash Tables with Linear Probing
4. Write a Program to Implement Hash Tables Chaining with Binary Trees
5. Write a Program to Implement Hash Tables Chaining with Doubly Linked Lists

Module- IV
Graph: Basic terminologies and Representation Traversal algorithms Breadth First Search,
Depth First Search, Shortest path: Depth first search in directed and undirected graphs. Union-
find data structure and applications. Directed acyclic graphs, topological sort.

Trees: Binary Search Trees, Definition, Implementation, Operations- Searching, Insertion and
Deletion, AVL Trees, Definition, Height of an AVL Tree, Operations – Insertion, Deletion and
Searching, Red –Black, Splay Trees.

Programs:
1. Write a program to implement the Binary Search tree.
a) Insertion b) Deletion c) Traversal d) Searching element in tree.

2. Write a program to implement the AVL tree.


a) Insertion b) Deletion c) Traversal d) Searching element in tree.

3. Write a program to implement the Red-Black tree.

4
Hyderabad Institute of Technology and Management

a) Insertion b) Deletion

4. Write a program to implement the Splay tree.

a) Insertion b) Deletion
5. Write a program to implement graph traversal methods
a) Breadth First Search, b) Depth First Search

Module V
Sorting: objective and Properties of different sorting Algorithms Insertion Sort, Bubble sort,
Selection Sort, Merge sort, Quick Sort, Heap sort, Radix sort, Bucket sort. Performance and
comparison among all the methods

Pattern Matching and Tries: Pattern matching algorithms-Brute force, The Boyer –Moore
algorithm, Naive algorithm, The Knuth-Morris-Pratt algorithm; Tries- Standard Tries,
Compressed Tries, Suffix tries.
Programs:
1. Write a program to implement merge sort using divide and conquer technique
2. Write a program to implement bubble sort.
3. Write a program to implement brute-force method of string matching.
4. Write a Program to perform string matching using Naive String Matching
5. Write a program to implement Standard Trie
6. Write a program to implement Compressed Trie
7. Write a program to implement Suffix Trie

TEXT BOOKS:
1. Fundamentals of Data Structures in C, 2nd Edition, E. Horowitz, S. Sahni and Susan
Anderson Freed, Universities Press.
2. Data Structures using C – A. S. Tanenbaum, Y. Langsam, and M.J. Augenstein,
PHI/Pearson Education.
3. AV Aho. J. Hopcroft, JD Ullman, Data Structures and Algorithms, Addison-
Wesley,1983.

REFERENCE BOOKS:
1. Data Structures : A Pseudocode Approach with C, 2nd Edition, R. F. Gilberg and
B.A. Forouzan, Cengage Learning.
2. Fundamentals of Computer Algorithms by Horwitz and Sahni,Galgotia.
3. Mark Allen Weiss, "Data Structures and Algorithm Analysis in C", 2nd Edition,
Pearson Education, 2011.

5
Hyderabad Institute of Technology and Management
Gowdavelli (V), Medchal (D)
Department of CSE(IOT)/CSE(DS)

Name of the Faculty: Aparna Gullapelly DEPT:ET Branch/Sem: II-III SEM Regulation:HR22
SUB: Data Structures and Algorithms
S.No Planne Topic Textbo No. Execu Pedagogy Topic Level Topic Level Outcomes Remark Sign of
d date ok of ted Keywords s Verifier
Hour date UNIT-I
1 Introduction to Data T1 1 Chalk & Talk Linear and Non- Understand types of Data
Structure, Application, linear Data Structure and its
Objectives Structure applications
2 Prerequisite: 1 Brainstorming Algorithm, Loops, Clear all doubts of
Algorithm, Loops in C, Array prerequisite topics
Array
3 Prerequisite: 1 Brainstorming Algorithm, Loops, Clear all doubts of
Algorithm, Loops in C, Array prerequisite topics
Array
4 Abstract data types T1 1 Chalk & Talk ADT Write the ADT of any data
structure
5 Dynamic aspects of T1 1 Chalk & Talk, Dynamic Memory Understand the dynamic
operations on data, Demonsration Allocation, aspects of data structure
Characteristics of data Operation on Data
structures Structure
6 Creation and T1 1 Chalk & Talk Operation on Data Understand the basic
manipulation of data Structure operations of data
structures, Operations structures
on data structures.
7 Algorithm: Asymptotic T1 1 Brainstorming, Big-Oh, Big- Find the resource
Notations Chalk & Talk Omega, Big-Theta consumption of algorithm
Notation
8 Asymptotic notations to T1 1 Brainstorming, Big-Oh, Big- Find the resource
calculate the running Chalk & Talk Omega, Big-Theta consumption of algorithm
time complexity of any Notation
algorithm. Ο Notation
(Big-O Notation), Ω
Notation (Big-Omega
Notation), θ Notation
(Theta Notation)
9 Calculate complexity T1 1 Brainstorming, Big-Oh, Big- Find the resource
analysis of control Chalk & Talk Omega, Big-Theta consumption of algorithm
structures Notation
10 Divide & conquer T1 1 Brainstorming, Big-Oh, Big- Differenciate Iterative and
recursion, Analyzing Chalk & Talk Omega, Big-Theta Recursive Algorithm
recursive algorithms. Notation
11 Calculate complexity T1 1 Brainstorming, Big-Oh, Big- Differenciate Iterative and
analysis of any Chalk & Talk Omega, Big-Theta Recursive Algorithm
recursive algorithm Notation
12 Revision and 1 Brainstorming, Clear all previous doubts
Assessment Test Moodle / Google
Form
12
UNIT-II
13 Prerequisite: Pointer, 1 Brainstorming Pointer, Structure Clear all doubts of
Structure prerequisite topics
14 Linked lists: Types of T2 1 Roleplay Linked List, Differentiate Array and
linked lists – singly, Advantages of Linked List
doubly and circularly Linked List
linked lists, operations
on linked lists.
15 Write a program that T2 2 Demonstration Linked List Implement Linked List
uses functions to
perform the following
operations on Singly
linkedlist. i) Creation ii)
Insertion iii) Deletion
iv) Traversal
16 Write a program that T2 2 Demonstration Circular Linked Implement Circular
uses functions to List Linked List
perform the following
operations on Circular
linkedlist. i) Creation ii)
Insertion iii) Deletion
iv)Traversal
17 Stack – Definition, T1 1 Roleplay Stack, Push, Pop Understand basic concepts
Stack Operations, Array of Stack
Representation of
Stacks
18 Write a program that T2 1 Demonstration Stack, Dynamic Implement stack
implement stack (its Array
operations) using
Pointers
19 Write a Program to T2 2 Demonstration Stack, Dynamic Implement stack
Implement Stack Array
Operations using
Dynamic Memory
Allocation.
20 Applications of Stacks, T1 1 Chalk & Talk Infix, Postfix, Understand application
Notations – infix, prefix Prefix area of stack
and postfix

21 Infix to postfix T1 1 Chalk & Talk Infix, Postfix, Solve problems related to
conversion, evaluation Prefix polish notation
of postfix expression.
22 Write a program to T2 2 Demonstration Infix, Postfix, Solve problems related to
convert expressions Prefix polish notation
infix to postfix using
stack.
23 Write a program to T2 1 Demonstration Infix, Postfix, Solve problems related to
evaluate arithmetic Prefix polish notation
expressions using stack

24 Implementation of T1 1 Roleplay Queue Understand basic concepts


queues– array and of Queue
linked list, operations
on queues
25 Write a program that T2 1 Demonstration Queue Understand basic concepts
implement Queue (its of Queue
operations) using
Arrays.
26 Types of queues – T1 1 Roleplay Circular Queue Differentiate Queue and
queue, double ended Circular queue
queue and priority
queue.
27 Revision and 1 Brainstorming, Clear all previous doubts
Assessment Test Moodle / Google
Form
19
UNIT-III
28 Dictionaries: Linear list T2 1 PPT Dictionaries Understand about
representation, Dictionaries
29 Write a program to T2 2 Brainstorming Dictionaries Understand about
implement dictionary Dictionaries
linear list representation
and its operations

30 skip list representation, T2 2 Roleplay Skip List, Differentiate Linked List


operations - insertion, Advantages of and Skip List List
deletion and searching. Skip List

31 Hash Table T1 1 Chalk & Talk RDM, FM, MM Solve problem related to
Representation: hash any hash function
functions
32 open addressing-linear T1 1 Chalk & Talk linear probing, Understand Collision
probing, quadratic quadratic probing, Resolution Techniques
probing, double hashing double hashing

33 Write a Program to T2 2 Demonstration linear probing Understand Collision


Implement Hash Tables Resolution Techniques
with Linear Probing

34 Write a Program to T1 1 Demonstration quadratic probing Understand Collision


Implement Hash Tables Resolution Techniques
with Quadratic Probing

35 Resolution-separate T1 1 Chalk & Talk separate chaining, Understand Collision


chaining, rehashing, rehashing, Resolution Techniques
extendible hashing extendible hashing

36 Write a Program to T2 2 Demonstration separate chaining Understand Collision


Implement Hash Tables Resolution Techniques
Chaining with Doubly
Linked Lists
37 Revision and 1 Brainstorming, Clear all previous doubts
Assessment Test Moodle / Google
Form
14
UNIT-IV
38 Graphs: Definitions, T1 1 Chalk & Talk Graph, Adjacency Understand about Graph
Terminologies, Matrix Matrix, Adjacency representation
and Adjacency List List
Representation of
Graphs
39 Traversal methods: T1 1 Chalk & Talk BFS & DFS Solve problems related to
Breadth First Search graph travarsal
and Depth First
Search.with deadlines
40 Write a program to T2 2 Demonstration BFS & DFS Solve problems related to
implement graph graph travarsal
traversal methods a)
Breadth First Search, b)
Depth First Search
41 Shortest path: Depth T1 2 Chalk & Talk Dijikstra's Solve problems related to
first search in directed Algorithm, Floyad shortest Path
and undirected graphs. Warshall
Algorithm
42 Directed acyclic graphs, T1 1 Chalk & Talk acyclic graph, Understand about
topological sort topological sort topological sort

43 Trees: Binary Search T1 2 Chalk & Talk Binary Search Differentiate Binary tree
Trees, Definition, Trees and Binary Search Tree
Implementation,
Operations- Searching,
Insertion and Deletion
44 Write a program to T2 2 Demonstration Binary Search Differentiate Binary tree
implement the Binary Trees and Binary Search Tree
Search tree.
a) Insertion b) Deletion
c) Traversal d)
Searching element in
tree.
45 AVL Trees, Definition, T2 2 Problem solving Balanced Tree, Build AVL Tree
Height of an AVL Tree, AVL Tree
Operations – Insertion,
Deletion and Searching

46 Write a program to T2 2 Demonstration Balanced Tree, Build AVL Tree


implement the AVL AVL Tree
tree. a) Insertion b)
Deletion c) Traversal d)
Searching element in
tree.
47 Red –Black Tree T1 1 PPT Red Black trees. Understand Red Black
Trees
48 Splay trees T1 1 PPT Splay trees Differentiate Splay Tree
and AVL Tree
49 Revision and 1 Brainstorming, Clear all previous doubts
Assessment Test Moodle / Google
Form
18
UNIT-V
50 Objective and T1 1 Roleplay, Bubble sort Apply different sorting
Properties of different Demonsration algorithms in relevant
sorting Algorithms, applications
Write a program to
implement bubble sort.
51 Insertion Sort T1 1 Roleplay, Insertion sort Apply different sorting
Demonsration algorithms in relevant
applications
52 Selection Sort T1 1 Roleplay, Selection sort Apply different sorting
Demonsration algorithms in relevant
applications
53 Merge sort T1 2 Roleplay, Merge sort Apply different sorting
Demonsration algorithms in relevant
applications
54 Quick Sort T1 2 Roleplay, Quick sort Apply different sorting
Demonsration algorithms in relevant
applications
55 Heap sort, Radix sort, T1 1 Chalk & Talk Sorting Apply different sorting
Bucket sort. algorithms in relevant
Performance and applications
comparison among all
the methods
56 Pattern Matching T1 1 Problem solving Pattern Matching, Understand Pattern
Algorithms- Brute Brute force, Boyer Matching Algorithms
force, Boyer Moore Moore
57 Write a program to T1 1 Problem solving, Pattern Matching, Understand Pattern
implement brute-force Demonstration Brute force, Boyer Matching Algorithms
method of string Moore
matching.
58 Knuth Morris Pratt T1 1 Problem solving Pattern Matching, Understand advantage of
Algorithm KMP Algorithm KMP Algorithm
59 Tries- standard tries, T1 1 Problem solving Tries, Suffix Tries Use Suffix Tries in pattern
compressed tries, suffix mtaching
tries.
60 Write a program to T1 1 Demonstration Tries Use Tries in pattern
implement Standard mtaching
Trie
61 Write a program to T1 1 Demonstration Tries Use Tries in pattern
implement Compressed mtaching
Trie
62 Write a program to T1 1 Demonstration Suffix Tries Use Suffix Tries in pattern
implement Suffix Trie mtaching
63 Revision and 1 Brainstorming, Clear all previous doubts
Assessment Test Moodle / Google
Form
No.of Hours: 16
Total No.of Hours: 79

Course Outcomes:
After completion of this course the student is able to
CO1: Understand concepts of ADT and to write an algorithm for a given problem statement, also calculate time and space complexity. - PO1,
CO2: Develop C programs for computing real-life applications using data structures like linked lists, stacks,queues. - PO1, PO2, PO3, PSO1
CO3: Understand different types of trees like Red-Black, AVL, Splay trees. - PO1, PO2, PO3, PO5, PSO1
CO4: Implement searching and sorting algorithms, and pattern matching algorithms. - PO1, PO2, PO3, PO5, PSO1

Projects:
1) Phone directory application using doubly-linked lists.
2) Search engine for data structures.
3) Knight’s travails Game.

TEXT BOOKS:
T1. Fundamentals of Data Structures in C, 2nd Edition, E. Horowitz, S. Sahni and Susan, Anderson Freed, Universities Press.
T2. Data Structures using C – A. S. Tanenbaum, Y. Langsam, and M.J. Augenstein, PHI/Pearson Education.
REFERENCE BOOKS:
R1. Data Structures : A Pseudocode Approach with C, 2nd Edition, R. F. Gilberg and B.A. Forouzan, Cengage Learning.
R2. Fundamentals of Computer Algorithms by Horwitz and Sahni,Galgotia.
R3. Mark Allen Weiss, "Data Structures and Algorithm Analysis in C", 2nd Edition, Pearson Education, 2011.

FACULTY HOD
Course Outcomes:

➢ Understand concepts of ADT and write an algorithm for a given problem statement,
also calculate time and space complexity.
➢ Develop C programs for computing real-life applications using data structures like
linked lists, stacks, and queues.
➢ Understand different types of trees like Red-Black, AVL, and Splay trees.
➢ Implement sorting algorithms and pattern-matching algorithms.

Course Projects:

1) Phone directory application using doubly-linked lists.


2) Search engine for data structures.
3) Knight’s travails Game.

11
Notes:

Primitive Data Structure:- The data structure that are atomic or indivisible are called primitive.
Example are integer, real, float, Boolean and characters.
Non-Primitive data structure:- The data structure that are not atomic are called non primitive or
composite.
Examples are records, arrays and strings. These are more sophisticated. The non-primitive data
structures emphasize on structuring a group of homogenous or heterogeneous data items.

Linear Data Structure:- In a linear data structure, the data items are arranged in a linear sequence.
Example is array.
Non Linear data structure:- In a non-linear data structure, the data items are not in sequence.
Example is tree.

Static Data Structure:- Static structures are ones whose sizes, structures, and associated memory
location are fixed at compile time.
Dynamic Data Structure:- Dynamic structures are ones which expand or shrink as required during
the program execution and their associated memory location changes.

Operations on data structure

Design of efficient data structure must take operations to be performed on the data structures into
account. The most
 Create:- The create operation results in reserving memory for program elements. This can
be done by declaration statement. Creation of data structure may take place either during
compile-time or run-time. malloc() function of C language is used for creation.
 Destroy:- Destroy operation destroys memory space allocated for specified data structure.
free() function of C language is used to destroy data structure.
 Selection:- Selection operation deals with accessing a particular data within a data structure.
 Updation:- It updates or modifies the data in the data structure.
• Searching:- It finds the presence of desired data item in the list of data items, it may also
find the locations of all elements that satisfy certain conditions.
• Sorting:- Sorting is a process of arranging all data items in a data structure in a particular
order, say for example, either in ascending order or in descending order.
• Merging:- Merging is a process of combining the data items of two different sorted list into
a single sorted list.
• Splitting:- Splitting is a process of partitioning single list to multiple list.
• Traversal:- Traversal is a process of visiting each and every node of a list in systematic
manner.

Algorithms

• Algorithm is a step-by-step procedure, which defines a set of instructions to be executed in


a certain order to get the desired output. Algorithms are generally created independent of
underlying languages, i.e. an algorithm can be implemented in more than one programming
language.

Not all procedures can be called an algorithm. An algorithm should have the following
characteristics −
Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases), and
their inputs/outputs should be clear and must lead to only one meaning.
Input − An algorithm should have 0 or more well-defined inputs.
Output − An algorithm should have 1 or more well-defined outputs, and should match the desired
output.
Finiteness − Algorithms must terminate after a finite number of steps.
Feasibility − Should be feasible with the available resources.
Independent − An algorithm should have step-by-step directions, which should be independent of
any programming code.

How to Write an Algorithm?

Not all procedures can be called an algorithm. An algorithm should have the following
characteristics −
• Unambiguous − Algorithm should be clear and unambiguous. Each of its steps (or phases),
and their inputs/outputs should be clear and must lead to only one meaning.
• Input − An algorithm should have 0 or more well-defined inputs.
• Output − An algorithm should have 1 or more well-defined outputs, and should match the
desired output.
• Finiteness − Algorithms must terminate after a finite number of steps.
• Feasibility − Should be feasible with the available resources.
• Independent − An algorithm should have step-by-step directions, which should be
independent of any programming code.

Example of an Algorithm
Let's try to learn algorithm-writing by using an example.
Problem − Design an algorithm to add two numbers and display the result.

Step 1 − START ADD


Step 2 − get values of a & b
Step 3 − c ← a + b
Step 4 − display c
Step 5 − STOP

Writing step numbers, is optional.


We design an algorithm to get a solution of a given problem. A problem can be solved in more than
one ways.

Algorithm Analysis

Efficiency of an algorithm can be analyzed at two different stages, before implementation and after
implementation. They are the following −
• A Priori Analysis − This is a theoretical analysis of an algorithm. Efficiency of an algorithm
is measured by assuming that all other factors, for example, processor speed, are constant
and have no effect on the implementation.
• A Posterior Analysis − This is an empirical analysis of an algorithm. The selected algorithm
is implemented using programming language. This is then executed on target computer
machine. In this analysis, actual statistics like running time and space required, are collected.
We shall learn about a priori algorithm analysis. Algorithm analysis deals with the execution or
running time of various operations involved. The running time of an operation can be defined as
the number of computer instructions executed per operation.

Algorithm Complexity

Suppose X is an algorithm and n is the size of input data, the time and space used by the
algorithm X are the two main factors, which decide the efficiency of X.
• Time Factor − Time is measured by counting the number of key operations such as
comparisons in the sorting algorithm.
• Space Factor − Space is measured by counting the maximum memory space required by
the algorithm.
The complexity of an algorithm f(n) gives the running time and/or the storage space required by
the algorithm in terms of n as the size of input data.
Space Complexity

Space complexity of an algorithm represents the amount of memory space required by the algorithm
in its life cycle. The space required by an algorithm is equal to the sum of the following two
components −
• A fixed part that is a space required to store certain data and variables, that are independent
of the size of the problem. For example, simple variables and constants used, program size,
etc.
• A variable part is a space required by variables, whose size depends on the size of the
problem. For example, dynamic memory allocation, recursion stack space, etc.
Space complexity S(P) of any algorithm P is S(P) = C + SP(I), where C is the fixed part and S(I) is
the variable part of the algorithm, which depends on instance characteristic I. Following is a simple
example that tries to explain the concept −
Algorithm: SUM(A, B)
Step 1 - START
Step 2 - C ← A + B + 10
Step 3 - Stop
Here we have three variables A, B, and C and one constant. Hence S(P) = 1 + 3. Now, space depends
on data types of given variables and constant types and it will be multiplied accordingly.

Time Complexity

Time complexity of an algorithm represents the amount of time required by the algorithm to run to
completion. Time requirements can be defined as a numerical function T(n), where T(n) can be
measured as the number of steps, provided each step consumes constant time.
For example, addition of two n-bit integers takes n steps. Consequently, the total computational
time is T(n) = c ∗ n, where c is the time taken for the addition of two bits. Here, we observe that
T(n) grows linearly as the input size increases.

Asymptotic Analysis

Asymptotic analysis of an algorithm refers to defining the mathematical boundation/framing of its


run-time performance. Using asymptotic analysis, we can very well conclude the best case, average
case, and worst case scenario of an algorithm.
Asymptotic analysis is input bound i.e., if there's no input to the algorithm, it is concluded to work
in a constant time. Other than the "input" all other factors are considered constant.
Asymptotic analysis refers to computing the running time of any operation in mathematical units
of computation. For example, the running time of one operation is computed as f(n) and may be for
another operation it is computed as g(n2). This means the first operation running time will increase
linearly with the increase in n and the running time of the second operation will increase
exponentially when n increases. Similarly, the running time of both operations will be nearly the
same if n is significantly small.
Usually, the time required by an algorithm falls under three types −
• Best Case − Minimum time required for program execution.
• Average Case − Average time required for program execution.
• Worst Case − Maximum time required for program execution.
Asymptotic Notations
Following are the commonly used asymptotic notations to calculate the running time complexity of
an algorithm.
• Ο Notation
• Ω Notation
• θ Notation

Big Oh Notation, Ο
The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It
measures the worst case time complexity or the longest amount of time an algorithm can possibly
take to complete.

For example, for a function f(n)

Ο(f(n)) = { g(n) : there exists c > 0 and n0 such that f(n) ≤ c.g(n) for all n > n0. }

Omega Notation, Ω
The notation Ω(n) is the formal way to express the lower bound of an algorithm's
running time. It measures the best case time complexity or the best amount of time
an algorithm can possibly take to complete.

For example, for a function f(n)


Ω(f(n)) ≥ { g(n) : there exists c > 0 and n0 such that g(n) ≤ c.f(n) for all n > n0. }

Theta Notation, θ
The notation θ(n) is the formal way to express both the lower bound and the upper
bound of an algorithm's running time. It is represented as follows −

For example, for a function f(n)


θ(f(n)) = { g(n) if and only if g(n) = Ο(f(n)) and g(n) = Ω(f(n)) for all n > n0. }

Common Asymptotic Notations

constant − Ο(1)

logarithmic − Ο(log n)

linear − Ο(n)

n log n − Ο(n log n)


quadratic − Ο(n2)

cubic − Ο(n3)

Recursion

Definition of Recursive function:


A function which contains call to itself or call to another function.
Base Case/ Terminal Condition: It is a special case whose solution can be obtained without using
recursion.
General Case: It contains the logic required to reduce the size of the problem, so as to move
towards the base case.

Recursion - Fibonacci : It is a series of numbers such that each number is sum of


previous two numbers, except first and second number.
1. We divide the large problem into multiple subproblems.
2. Solve the subproblem and store the result.
3. Using the subproblem result, we can build the solution for the large problem.

Base Case/ Terminal Condition: It is a special case whose solution can be


obtained without using recursion.
General Case: It contains the logic required to reduce the size of the problem, so as
to move towards the base case.
Output:

0 1 1 2 3 5 8 13 21 34
Question Bank
Recursion is the process of repeating items in a self-similar way. In programming languages, if
a program allows you to call a function inside the same function, then it is called a recursive call
of the function.

The C programming language supports recursion, i.e., a function to call itself. But while using
recursion, programmers need to be careful to define an exit condition from the function,
otherwise it will go into an infinite loop.

The following example calculates the factorial of a given number using a recursive function
Output:

Factorial of 12 is 479001600

Sorting

How Bubble Sort Works

The bubble sort starts with the very first index and makes it a bubble element. Then it
compares the bubble element, which is currently our first index element, with the next
element. If the bubble element is greater and the second element is smaller, then both of them
will swap.
After swapping, the second element will become the bubble element. Now we will compare
the second element with the third as we did in the earlier step and swap them if required. The
same process is followed until the last element.

We will follow the same process for the rest of the iterations. After each of the iteration, we
will notice that the largest element present in the unsorted array has reached the last index.

For each iteration, the bubble sort will compare up to the last unsorted element.

Once all the elements get sorted in the ascending order, the algorithm will get terminated.
Consider the following example of an unsorted array that we will sort with the help of the
Bubble Sort algorithm.

Pass 1:

Compare a0 and a1

As a0 < a1 so the array will remain as it is.

Compare a1 and a2

Now a1 > a2, so we will swap both of them.

Compare a2 and a3
As a2 < a3 so the array will remain as it is.

Compare a3 and a4

Here a3 > a4, so we will again swap both of them.

Pass 2:

• Compare a0 and a1

As a0 < a1 so the array will remain as it is.

• Compare a1 and a2
Here a1 < a2, so the array will remain as it is.

Compare a2 and a3

In this case, a2 > a3, so both of them will get swapped.

Pass 3:

Compare a0 and a1

As a0 < a1 so the array will remain as it is.

Compare a1 and a2
Now a1 > a2, so both of them will get swapped.

Pass 4:

• Compare a0 and a1

Here a0 > a1, so we will swap both of them.

Complexity Analysis of Bubble Sort

Input: Given n input elements.

Output: Number of steps incurred to sort a list.

Logic: If we are given n elements, then in the first pass, it will do n-1 comparisons; in the second
pass, it will do n-2; in the third pass, it will do n-3 and so on. Thus, the total number of
comparisons can be found by;
Therefore, the bubble sort algorithm encompasses a time complexity of O(n2) and a space
complexity of O(1) because it necessitates some extra memory space for temp variable for
swapping.

• Best Case Complexity: The bubble sort algorithm has a best-case time complexity of O(n)
for the already sorted array.
• Average Case Complexity: The average-case time complexity for the bubble sort
algorithm is O(n2), which happens when 2 or more elements are in jumbled, i.e., neither in
the ascending order nor in the descending order.
• Worst Case Complexity: The worst-case time complexity is also O(n2), which occurs
when we sort the descending order of an array into the ascending order.

Advantages of Bubble Sort

1. Easily understandable.
2. Does not necessitates any extra memory.
3. The code can be written easily for this algorithm.
4. Minimal space requirement than that of other sorting algorithms.

Disadvantages of Bubble Sort

1. It does not work well when we have large unsorted lists, and it necessitates more resources
that end up taking so much of time.
2. It is only meant for academic purposes, not for practical implementations.
3. It involves the n2 order of steps to sort an algorithm.

Selection Sort

The selection sort enhances the bubble sort by making only a single swap for each pass through
the rundown. In order to do this, a selection sort searches for the biggest value as it makes a pass
and, after finishing the pass, places it in the best possible area. Similarly, as with a bubble sort,
after the first pass, the biggest item is in the right place. After the second pass, the following
biggest is set up. This procedure proceeds and requires n-1 goes to sort n item since the last item
must be set up after the (n-1) th pass.

ALGORITHM: SELECTION SORT (A)

1. k ← length [A]

2. for j ←1 to n-1

3. smallest ← j
4. for I ← j + 1 to k

5. if A [i] < A [ smallest]

6. then smallest ← i

7. exchange (A [j], A [smallest])

1. In the selection sort, first of all, we set the initial element as a minimum.
2. Now we will compare the minimum with the second element. If the second element turns
out to be smaller than the minimum, we will swap them, followed by assigning to a
minimum to the third element.
3. Else if the second element is greater than the minimum, which is our first element, then we
will do nothing and move on to the third element and then compare it with the minimum.
We will repeat this process until we reach the last element.
4. After the completion of each iteration, we will notice that our minimum has reached the
start of the unsorted list.
5. For each iteration, we will start the indexing from the first element of the unsorted list. We
will repeat the Steps from 1 to 4 until the list gets sorted or all the elements get correctly
positioned.
Consider the following example of an unsorted array that we will sort with the help of the
Selection Sort algorithm.
6. A [] = (7, 4, 3, 6, 5).
A [] =

1st Iteration:
Set minimum = 7
Compare a0 and a1

As, a0 > a1, set minimum = 4


Compare a1 and a2
Compare a1 and a2

As, a1 > a2, set minimum = 3.

Compare a2 and a3

As, a2 < a3, set minimum= 3.

Compare a1 and a2

As, a1 > a2, set minimum = 3.

Compare a2 and a3

As, a2 < a3, set minimum= 3.

• Compare a2 and a4

As, a2 < a4, set minimum =3.

Since 3 is the smallest element, so we will swap a0 and a2.


• 2nd Iteration:

Set minimum = 4
Compare a1 and a2

As, a1 < a2, set minimum = 4.

• Compare a1 and a3

As, A[1] < A[3], set minimum = 4.

• Compare a1 and a4

Again, a1 < a4, set minimum = 4.

Since the minimum is already placed in the correct position, so there will be no
swapping.

3rd Iteration:

Set minimum = 7

Compare a2 and a3
As, a2 > a3, set minimum = 6.

• Compare a3 and a4

As, a3 > a4, set minimum = 5.

Since 5 is the smallest element among the leftover unsorted elements, so we will
swap 7 and 5.

4th Iteration:

Set minimum = 6

• Compare a3 and a4

As a3 < a4, set minimum = 6.

Since the minimum is already placed in the correct position, so there will be no
swapping.
Input: Given n input elements.
Output: Number of steps incurred to sort a list.

Logic: If we are given n elements, then in the first pass, it will do n-1 comparisons; in the second pass, it
will do n-2; in the third pass, it will do n-3 and so on. Thus, the total number of comparisons can be found
by;

Therefore, the selection sort algorithm encompasses a time complexity of O(n2) and a space
complexity of O(1) because it necessitates some extra memory space for temp variable for
swapping.

Time Complexities:

• Best Case Complexity: The selection sort algorithm has a best-case time complexity of
O(n2) for the already sorted array.
• Average Case Complexity: The average-case time complexity for the selection sort
algorithm is O(n2), in which the existing elements are in jumbled ordered, i.e., neither in
the ascending order nor in the descending order.
• Worst Case Complexity: The worst-case time complexity is also O(n2), which occurs
when we sort the descending order of an array into the ascending order.

In the selection sort algorithm, the time complexity is O(n2) in all three cases. This is because,
in each step, we are required to find minimum elements so that it can be placed in the correct
position. Once we trace the complete array, we will get our minimum element.

Insertion Sort

• Insertion sort is one of the simplest sorting algorithms for the reason that it sorts a single
element at a particular instance. It is not the best sorting algorithm in terms of
performance, but it's slightly more efficient than selection sort and bubble sort in practical
scenarios. It is an intuitive sorting technique.
• Let's consider the example of cards to have a better understanding of the logic behind the
insertion sort.
• Suppose we have a set of cards in our hand, such that we want to arrange these cards in
ascending order. To sort these cards, we have a number of intuitive ways.
• One such thing we can do is initially we can hold all of the cards in our left hand, and we
can start taking cards one after other from the left hand, followed by building a sorted
arrangement in the right hand.
• Assuming the first card to be already sorted, we will select the next unsorted card. If the
unsorted card is found to be greater than the selected card, we will simply place it on the
right side, else to the left side. At any stage during this whole process, the left hand will be
unsorted, and the right hand will be sorted.
• In the same way, we will sort the rest of the unsorted cards by placing them in the correct
position. At each iteration, the insertion algorithm places an unsorted element at its right
place.

ALGORITHM: INSERTION SORT (A)

1. for j = 2 to A.length
2. key = A[j]
3. // Insert A[j] into the sorted sequence A[1.. j - 1]
4. i = j - 1
5. while i > 0 and A[i] > key
6. A[i + 1] = A[i]
7. ii = i -1
8. A[i + 1] = key

How Insertion Sort Works

1. We will start by assuming the very first element of the array is already sorted. Inside the key, we will
store the second element.
Next, we will compare our first element with the key, such that if the key is found to be smaller than the
first element, we will interchange their indexes or place the key at the first index. After doing this, we will
notice that the first two elements are sorted.
2. Now, we will move on to the third element and compare it with the left-hand side elements. If it is the
smallest element, then we will place the third element at the first index.
Else if it is greater than the first element and smaller than the second element, then we will interchange its
position with the third element and place it after the first element. After doing this, we will have our first
three elements in a sorted manner.
3. Similarly, we will sort the rest of the elements and place them in their correct position.
Time Complexities:

• Best Case Complexity: The insertion sort algorithm has a best-case time complexity of
O(n) for the already sorted array because here, only the outer loop is running n times, and
the inner loop is kept still.
• Average Case Complexity: The average-case time complexity for the insertion sort
algorithm is O(n2), which is incurred when the existing elements are in jumbled order, i.e.,
neither in the ascending order nor in the descending order.
• Worst Case Complexity: The worst-case time complexity is also O(n2), which occurs
when we sort the ascending order of an array into the descending order.
In this algorithm, every individual element is compared with the rest of the elements, due
to which n-1 comparisons are made for every nth element.

Space Complexity

The insertion sort encompasses a space complexity of O(1) due to the usage of an extra
variable key.

Insertion Sort Applications

The insertion sort algorithm is used in the following cases:


• When the array contains only a few elements.
• When there exist few elements to sort.

Advantages of Insertion Sort

1. It is simple to implement.
2. It is efficient on small datasets.
3. It is stable (does not change the relative order of elements with equal keys)
4. It is in-place (only requires a constant amount O (1) of extra memory space).
5. It is an online algorithm, which can sort a list when it is received.

Merge Sort

Merge Sort

Merge sort is yet another sorting algorithm that falls under the category of Divide and Conquer

technique. It is one of the best sorting techniques that successfully build a recursive algorithm.

Divide and Conquer Strategy

In this technique, we segment a problem into two halves and solve them individually. After
finding the solution of each half, we merge them back to represent the solution of the main
problem.

Suppose we have an array A, such that our main concern will be to sort the subsection, which
starts at index p and ends at index r, represented by A[p..r].
Divide

If assumed q to be the central point somewhere in between p and r, then we will fragment the
subarray A[p..r] into two arrays A[p..q] and A[q+1, r].

Conquer

After splitting the arrays into two halves, the next step is to conquer. In this step, we
individually sort both of the subarrays A[p..q] and A[q+1, r]. In case if we did not reach the
base situation, then we again follow the same procedure, i.e., we further segment these
subarrays followed by sorting them separately.

Combine

As when the base step is acquired by the conquer step, we successfully get our sorted subarrays
A[p..q] and A[q+1, r], after which we merge them back to form a new sorted array [p..r].

Merge Sort algorithm

The MergeSort function keeps on splitting an array into two halves until a condition is met
where we try to perform MergeSort on a subarray of size 1, i.e., p == r.

And then, it combines the individually sorted subarrays into larger arrays until the whole array
is merged.

1. ALGORITHM-MERGE SORT
2. 1. If p<r
3. 2. Then q → ( p+ r)/2
4. 3. MERGE-SORT (A, p, q)
5. 4. MERGE-SORT ( A, q+1,r)
6. 5. MERGE ( A, p, q, r)

Here we called MergeSort(A, 0, length(A)-1) to sort the complete array.

As you can see in the image given below, the merge sort algorithm recursively divides the
array into halves

until the base condition is met, where we are left with only 1 element in the array.

And then, the merge function picks up the sorted sub-arrays and merge them back to sort the
entire array.

The following figure illustrates the dividing (splitting) procedure.


FUNCTIONS: MERGE (A, p, q, r)

1. n 1 = q-p+1

2. n 2= r-q

3. create arrays [1.....n 1 + 1] and R [ 1.....n 2 +1 ]

4. for i ← 1 to n 1

5. do [i] ← A [ p+ i-1]

6. for j ← 1 to n2

7. do R[j] ← A[ q + j]

8. L [n 1+ 1] ← ∞

9. R[n 2+ 1] ← ∞
10. I ← 1

11. J ← 1

12. For k ← p to r

13. Do if L [i] ≤ R[j]

14. then A[k] ← L[ i]

15. i ← i +1

16. else A[k] ← R[j]

17. j ← j+1

The merge step of Merge Sort

Mainly the recursive algorithm depends on a base case as well as its ability to merge back the
results derived from the base cases. Merge sort is no different algorithm, just the fact here the
merge step possesses more importance.
To any given problem, the merge step is one such solution that combines the two individually
sorted lists(arrays) to build one large sorted list(array).

The merge sort algorithm upholds three pointers, i.e., one for both of the two arrays and the
other one to preserve the final sorted array's current index.

Merge( ) Function Explained Step-By-Step

Consider the following example of an unsorted array, which we are going to sort with the help
of the Merge Sort algorithm.

A= (36,25,40,2,7,80,15)

Step1: The merge sort algorithm iteratively divides an array into equal halves until we achieve
an atomic value. In case if there are an odd number of elements in an array, then one of the
halves will have more elements than the other half.

Step2: After dividing an array into two subarrays, we will notice that it did not hamper the
order of elements as they were in the original array. After now, we will further divide these two
arrays into other halves.

Step3: Again, we will divide these arrays until we achieve an atomic value, i.e., a value that
cannot be further divided.

Step4: Next, we will merge them back in the same way as they were broken down.

Step5: For each list, we will first compare the element and then combine them to form a new
sorted list.

Step6: In the next iteration, we will compare the lists of two data values and merge them back
into a list of found data values, all placed in a sorted manner.
Quick Sort
Randomized Quick Sort

A simple example is randomized QuickSort, where the pivot is chosen randomly, and divides
the elements into three partitions: elements less than pivot, elements equal to pivot, and elements
greater than pivot. The randomized QuickSort require a lot of resources but always generate the
sorted array as an output.
It is obvious that QuickSort always generates the solution which in this case the sorted array.
Unfortunately, the time complexity is not that obvious. It turns out that the running time depends
on which element we pick as a pivot.

# include <stdio.h>

#include <stdlib.h>

#include <time.h>

int getBig(int *a, int i, int right, int pivot)

for (int k = i; k <= right; k++)

if (a[k] > pivot)

return k;
}

return right + 1;

int getSmall(int *a, int j, int left, int pivot)

for (int k = j; k >= left; k--)

if (a[k] < pivot)

return k;

return -1;

void swap(int *a, int *b)

int t = *a;

*a = *b;

*b = t;

void random_quick(int *a, int left, int right)

if (left >= right)

return;

int index = left + (rand() % (right - left)), i = left, j = right;


int pivot_index = index;

int pivot = a[index];

// storing index of element greater than pivot

i = getBig(a, i, right, pivot);

// storing index of element smaller than pivot

j = getSmall(a, j, left, pivot);

while (i <= j)

swap(&a[i], &a[j]);

i = getBig(a, i, right, pivot);

j = getSmall(a, j, left, pivot);

// after separating the smaller and greater elements, there are 3 cases

// possible

if (pivot_index > j && pivot_index > i)

// case 1. When the pivot element index is greater than both i and j

swap(&a[i], &a[pivot_index]);

random_quick(a, left, i - 1);

random_quick(a, i + 1, right);

else if (pivot_index < j && pivot_index < i)

{
// case 2. When the pivot element index is smaller than both i and j

swap(&a[j], &a[pivot_index]);

random_quick(a, left, j - 1);

random_quick(a, j + 1, right);

else

// the pivot element is at its origin position.

random_quick(a, left, pivot_index - 1);

random_quick(a, pivot_index + 1, right);

int main()

srand(time(0));

int num;

printf("Input number of elements you want to sort: ");

scanf("%d", &num);

printf("\nInput the numbers:\n");

int *arr = (int *)malloc(num * sizeof(int));

for (int i = 0; i < num; i++)

scanf("%d", &arr[i]);
}

random_quick(arr, 0, num - 1);

printf("\nSorted array: ");

for (int i = 0; i < num; i++)

printf("%d ", arr[i]);

free(arr);

printf("\n");

Sample Output:
Input number of elements you want to sort: 5
Input the numbers:
10 20 30 40 50 60 70 80 90
Sorted array: 10 20 30 40 50
--------------------------------
Process exited after 25.93 seconds with return value 0
Press any key to continue . . .

Module 2

Stack

• A stack is a list of elements in which an element may be inserted or deleted only at one
end, called the top of the stack.
• The elements are removed from a stack in the reverse order of that in which they were
inserted into the stack.
• Stack is also known as a LIFO (Last in Fast out) list or Push down list.
• Some key points related to stack
• It is called as stack because it behaves like a real-world stack, piles of books, etc.
• A Stack is an abstract data type with a pre-defined capacity, which means that it can store
the elements of a limited size.
• It is a data structure that follows some order to insert and delete the elements, and that order
can be LIFO or FILO.

Standard Stack Operations

The following are some common operations implemented on the stack:

 push(): When we insert an element in a stack then the operation is known as a push.
If the stack is full then the overflow condition occurs.
 pop(): When we delete an element from the stack, the operation is known as a pop.
If the stack is empty means that no element exists in the stack, this state is known as
an underflow state.
 isEmpty(): It determines whether the stack is empty or not.
 isFull(): It determines whether the stack is full or not.
 peek(): It returns the element at the given position.
 count(): It returns the total number of elements available in a stack.
 change(): It changes the element at the given position.
 display(): It prints all the elements available in the stack.
POP operation

The steps involved in the POP operation is given below:

• Before deleting the element from the stack, we check whether the stack is empty.
• If we try to delete the element from the empty stack, then the underflow condition occurs.
• If the stack is not empty, we first access the element which is pointed by the top
• Once the pop operation is performed, the top is decremented by 1, i.e., top=top-1.

• Two standard error messages of stack are


– Stack Overflow: If we attempt to add new element beyond the maximum size, we
will encounter a stack overflow condition.
– Stack Underflow: If we attempt to remove elements beyond the base of the stack,
we will encounter a stack underflow condition.

Applications of Stack

String reversal: Stack is also used for reversing a string. For example, we want to reverse a
"javaTpoint" string, so we can achieve this with the help of a stack.

UNDO/REDO: It can also be used for performing UNDO/REDO operations. For example, we
have an editor in which we write 'a', then 'b', and then 'c'; therefore, the text written in an editor
is abc. So, there are three states, a, ab, and abc, which are stored in a stack. There would be two
stacks in which one stack shows UNDO state, and the other shows REDO state.
Recursion: The recursion means that the function is calling itself again. To maintain the
previous states, the compiler creates a system stack in which all the previous records of the
function are maintained.

Backtracking: Suppose we have to create a path to solve a maze problem. If we are moving in
a particular path, and we realize that we come on the wrong way. In order to come at the
beginning of the path to create a new path, we have to use the stack data structure.

Expression conversion: Stack can also be used for expression conversion. This is one of the
most important applications of stack. The list of the expression conversion is given below:

• Infix to prefix
• Infix to postfix
• Prefix to infix
• Prefix to postfix
• Postfix to infix.

Array implementation of Stack

• In array implementation, the stack is formed by using the array.


• All the operations regarding the stack are performed using arrays.

Adding an element onto the stack (push operation)

Adding an element into the top of the stack is referred to as push operation. Push operation
involves following two steps.

1. Increment the variable Top so that it can now refer to the next memory location.
2. Add element at the position of incremented top. This is referred to as adding new element
at the top of the stack.

Adding an element onto the stack (push operation)

1. begin
2. if top = n then stack full
3. top = top + 1
4. stack (top) : = item;
5. end

Deletion of an element from a stack (Pop operation)

Deletion of an element from the top of the stack is called pop operation.
The top most element of the stack is stored in an another variable and then the top is
decremented by 1.

The operation returns the deleted value that was stored in another variable.

The underflow condition occurs when we try to delete an element from an empty stack.

#include<stdio.h>
#include<stdlib.h>

#define SIZE 4
void push(int);
void pop();
void display();
int stack[SIZE], top = -1;

int main()
{

int value, choice;


while (1)
{
printf("\n\n**** MENU ****\n");
printf("1. Push\n2. Pop\n3. Display\n4. Exit");
printf("\nEnter your choice : ");
scanf("%d", & choice);
switch (choice)
{
case 1:
printf("enter the value to be inserted :");
scanf("%d", & value);
push(value);
break;
case 2:
pop();
break;
case 3:
display();
break;
case 4:
exit(0);
break;
default:
printf("\nWrong selection!! , Try again !!");
}
}
}

void push(int value)


{
if (top == SIZE - 1)
printf("\nStack is full!! insertion is not possible!!");
else
{
top++;
stack[top] = value;
printf("\n Insertion Success!!");
}
}

void pop()
{
if (top == -1)
printf("\nStack is empty , Deletion is not possible !!");
else {
printf("\nDeleted : %d", stack[top]);
top--;
}
}

void display()
{
if (top == -1)
printf("\nStack is empty!!");
else
{
int i;
printf("\nStack elements are :\n");
for (i = top; i >= 0; i--)
printf("%d\n", stack[i]);
}
}
• OUTPUT:

Implement Stack using Linked List.

Explanation: A stack can be easily implemented through the linked list. In stack Implementation,
a stack contains a top pointer. Which is “head” of the stack where pushing and popping items
happens at the head of the list. first node have null in link field and second node link have first
node address in link field and so on and last node address in “top” pointer.

The main advantage of using linked list over an arrays is that it is possible to implements a stack
that can shrink or grow as much as needed. In using array will put a restriction to the maximum
capacity of the array which can lead to stack overflow. Here each new node will be dynamically
allocate. so overflow is not possible.
Stack Operations:

push() : Insert the element into linked list nothing but which is the top node of Stack.

pop() : Return top element from the Stack and move the top pointer to the second node of linked
list or Stack.

peek(): Return the top element.

display(): Print all element of Stack.

Source Code:

# include <stdio.h>

# include <stdlib.h>

struct node

int data;

struct node *next;

};

typedef struct node NODE;

NODE *start = NULL;

int menu()

int ch;

system("cls");

printf("\n 1.Create a list ");

printf("\n--------------------------");

printf("\n 2. PUSH ");

printf("\n 3. POP");

printf("\n 4. Displaying the list");


printf("\n 5. Quit");

printf("\n--------------------------");

printf("\n\n Enter your choice: ");

scanf("%d",&ch);

return ch;

NODE* getnode()

NODE * newnode;

newnode = (NODE *) malloc(sizeof(NODE));

printf("\n Enter data: ");

scanf("%d", &newnode -> data);

newnode -> next = NULL;

return newnode;

void createlist(int n)

int i;

NODE *newnode, *temp;

for(i = 0; i < n; i++)

newnode = getnode();

if(start == NULL)

start = newnode;
}

else

temp = start;

while(temp -> next != NULL)

temp = temp -> next;

temp -> next = newnode;

void display()

NODE *temp;

temp = start;

printf("\n The contents of List (Left to Right): \n");

if(start == NULL)

printf("\n Empty List");

return;

else

while(temp != NULL)

printf("%d-->", temp -> data);


temp = temp -> next;

void push()

NODE *newnode;

newnode = getnode();

if(start == NULL)

start = newnode;

else

newnode -> next = start;

start = newnode;

void pop()

NODE *temp;

if(start == NULL)

printf("\n No nodes are exist..");

return ;
}

else

temp = start;

start = temp -> next;

printf("\n Node deleted %d", temp->data);

free(temp);

void main(void)

int ch, n;

while(1)

ch = menu();

switch(ch)

case 1:

if(start == NULL)

printf("\n Number of nodes you want to create: ");

scanf("%d", &n);

createlist(n);

printf("\n List created..");

}
else

printf("\n List is already created..");

break;

case 2:

push();

break;

case 3:

pop();

break;

case 4:

display();

break;

case 5:

exit(0);

getch();

OUTPUT :

Create the List


Display

Expressions

An expression is a collection of operators and operands that represents a specific value.


An expression consists of constants, variables, and symbols.
Symbols can be operators or parenthesis.
All these components must be arranged according to a set of rules, so that all these expressions can
be evaluated using the set of rules.
Examples of expressions are:

1. 5+6 2. A–B 3. (P * 5)

Expression Types

Based on the operator position, expressions are divided into THREE types. They are as follows...

Infix Expression
Postfix Expression
Prefix Expression

Infix: It is the form of an arithmetic expression in which we fix (place) the arithmetic operator
in between the two operands. E.g.: (A + B) * (C - D)

Prefix: It is the form of an arithmetic notation in which we fix (place) the arithmetic operator
before (pre) its two operands. The prefix notation is called as polish notation. E.g.: * + A B –
CD

Postfix: It is the form of an arithmetic expression in which we fix (place) the arithmetic
operator after (post) its two operands. The postfix notation is called as suffix notation and is
also referred to reverse polish notation. E.g: A B + C D - *

When the operator is written in between the operands, then it is known as infix notation.
Operand does not have to be always a constant or a variable; it can also be an expression itself.

For example,

(p + q) * (r + s)

In the above expression, both the expressions of the multiplication operator are the operands,
i.e., (p + q), and (r + s) are the operands.

In the above expression, there are three operators. The operands for the first plus operator are p
and q, the operands for the second plus operator are r and s. While performing the operations
on the expression, we need to follow some set of rules to evaluate the result.
In the algebraic expression, the order of the operator precedence is given in the below table:

• Operators Symbols
• Parenthesis ( ), {}, [ ]
• Exponents ^
• Multiplication and Division *, /
• Addition and Subtraction +,-

Associativity

• Associativity describes the rule where operators with the same precedence appear in an
expression.
• For example, in the expression a + b − c, both + and – have the same precedence, then which
part of the expression will be evaluated first, is determined by associativity of those
operators. Here, both + and − are left associative, so the expression will be evaluated
as (a + b) − c.
• Precedence and associativity determine the order of evaluation of an expression. Following
is an operator precedence and associativity table (highest to lowest).

• The first preference is given to the parenthesis; then next preference is given to the
exponents. In the case of multiple exponent operators, then the operation will be applied
from right to left.
• For example:

2^2^3 = 2 ^ 8

= 256

• After exponent, multiplication, and division operators are evaluated. If both the operators
are present in the expression, then the operation will be applied from left to right.
• Operators that have the same precedence termed as operator associativity.
• If we go from left to right, then it is known as left-associative.
• If we go from right to left, then it is known as right-associative.

Problems with infix notation

• To evaluate the infix expression, we should know about the operator precedence rules, and
if the operators have the same precedence, then we should follow the associativity rules.
• The use of parenthesis is very important in infix notation to control the order in which the
operation to be performed. Parenthesis improves the readability of the expression.
• An infix expression is the most common way of writing expression, but it is not easy to
parse (resolve it into components) and evaluate the infix expression without ambiguity.
So, mathematicians and logicians studied this problem and discovered two other ways of
writing expressions which are prefix and postfix.
• Both prefix and postfix expressions do not require any parenthesis and can be parsed
without ambiguity. It does not require operator precedence and associativity rules.

Postfix Expression

• The postfix expression is an expression in which the operator is written after the operands.
For example, the postfix expression of infix notation ( 2+3) can be written as 23+.
• Some key points regarding the postfix expression are:
• In postfix expression, operations are performed in the order in which they have written from
left to right.
• It does not any require any parenthesis.
• We do not need to apply operator precedence rules and associativity rules.

Algorithm to evaluate the postfix expression

1. Scan the expression from left to right until we encounter any operator.
2. Perform the operation
3. Replace the expression with its computed value.
4. Repeat the steps from 1 to 3 until no more operators exist.
5. Let's understand the above algorithm through an example.
6. Infix expression: 2 + 3 * 4
7. We will start scanning from the left most of the expression. The multiplication operator
is an operator that appears first while scanning from left to right. Now, the expression
would be:
8. Expression = 2 + 34*
9. = 2 + 12
10. Again, we will scan from left to right, and the expression would be:
11. Expression = 2 12 +
12. = 14

Evaluation of postfix expression using stack.

1. Scan the expression from left to right.


2. If we encounter any operand in the expression, then we push the operand in the stack.
3. When we encounter any operator in the expression, then we pop the corresponding
operands from the stack.
4. When we finish with the scanning of the expression, the final value remains in the stack.

Let's understand the evaluation of postfix expression using stack.

Example 1: Postfix expression: 2 3 4 * +

Let's understand the evaluation of postfix expression using stack.


Algorithm

1. Scan the infix expression from left to right.

2. If the scanned character is an operand, output it.

3. Else,

1 If the precedence of the scanned operator is greater than the precedence of the operator in
the stack(or the stack is empty or the stack contains a ‘(‘ ), push it.

2 Else, Pop all the operators from the stack which are greater than or equal to precedence
than that of the scanned operator. After doing that Push the scanned operator to the stack. (If you
encounter parenthesis while popping then stop there and push the scanned operator in the stack.)

4. If the scanned character is an ‘(‘, push it to the stack.


5. If the scanned character is an ‘)’, pop the stack and output it until a ‘(‘ is encountered, and
discard both the parenthesis.

6. Repeat steps 2-6 until infix expression is scanned.

7. Print the output

8. Pop and output from the stack until it is not empty.

Example:
Queue
• A queue is a data structure where items are inserted at one end called the rear
and deleted at the other end called the front.
• Another name for a queue is a ―FIFO
• Operations of a Queue:
⮚ enqueue:which inserts an element at the end of the queue.
⮚ dequeue:which deletes an element at the front of the queue.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>

#define MAX 5
int insert();
int remove();
int display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
remove();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
}
}

int insert()
{
int add_item;
if (rear >= MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
}

int remove()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}

int display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}

Output:
Implement Queue using List

Explanation: In a Queue data structure, we maintain two pointers, front and rear. The front
points the first item of queue and rear points to last item.
enQueue() This operation adds a new node after rear and moves rear to the next node.
deQueue() This operation removes the front node and moves front to the next node.

Source Code:
# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *next;
};
typedef struct node NODE;
NODE *start = NULL;
int menu()
{
int ch;
system("cls");
printf("\n 1.Create a list ");
printf("\n--------------------------");
printf("\n 2.Insert Queue ");
printf("\n 3.Delete Queue");
printf("\n 4.Displaying the list");
printf("\n 5.Exit ");
printf("\n--------------------------");
printf("\n\n Enter your choice: ");
scanf("%d",&ch);
return ch;
}

NODE* getnode()
{
NODE * newnode;
newnode = (NODE *) malloc(sizeof(NODE));
printf("\n Enter data: ");
scanf("%d", &newnode -> data);
newnode -> next = NULL;
return newnode;
}
void createlist(int n)
{
int i;
NODE *newnode, *temp;
for(i = 0; i < n; i++)
{
newnode = getnode();
if(start == NULL)
{
start = newnode;
}
else
{
temp = start;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;
}
}
}
void display()
{
NODE *temp;
temp = start;
printf("\n The contents of List (Left to Right): \n");
if(start == NULL)
{
printf("\n Empty List");
return;
}
else
{
while(temp != NULL)
{
printf("%d-->", temp -> data);
temp = temp -> next;
}
}
}
void insertQ()
{
NODE *newnode, *temp;
newnode = getnode();
if(start == NULL)
{
start = newnode;
}
else
{
temp = start;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;
}
}
void deleteQ()
{
NODE *temp;
if(start == NULL)
{
printf("\n No nodes are exist..");
return ;
}
else
{
temp = start;
start = temp -> next;
printf("\n Node deleted %d", temp->data);
free(temp);
}
}
void main(void)
{
int ch, n;
while(1)
{
ch = menu();
switch(ch)
{
case 1:
if(start == NULL)
{
printf("\n Number of nodes you want to create: ");
scanf("%d", &n);
createlist(n);
printf("\n List created..");
}
else
printf("\n List is already created..");
break;
case 2:
insertQ();
break;
case 3:
deleteQ();
break;
case 4:
display();
break;
case 5:
exit(0);
break;
}
getch();
}
}
Output

List Creation
Display the List

Delete Operation
Applications of Queue

• It is used to schedule the jobs to be processed by the CPU.


• When multiple users send print jobs to a printer, each printing job is kept in
the printing queue. Then the printer prints those jobs according to first in
first out (FIFO) basis.

Circular Queue

• A circular queue is one in which the insertion of new element is done at the
very first location of the queue if the last location of the queue is full.
• Suppose if we have a Queue of n elements then after adding the element at
the last index

i.e. (n-1)th, as queue is starting with 0 index, the next element will be inserted at
the very first location of the queue which was not possible in the simple linear
queue.

• The Basic Operations of a circular queue are


⮚ InsertionCQ: Inserting an element into a circular queue results in
Rear = (Rear + 1) % MAX, where MAX is the maximum size of the
array.
⮚ DeletionCQ : Deleting an element from a circular queue results in
Front = (Front + 1) % MAX, where MAX is the maximum size of the
array.
⮚ TraversCQ: Displaying the elements of a circular Queue.
• Circular Queue Empty: Front=Rear=0.
Illustrate the implementation of circular queue using single linked list?

Sol:
Circular Queue:

● Front:Get the front item from queue.


● Rear: Get the last item from queue.

enQueue(value) - This function is used to insert an element into the circular queue. In a circular
queue, the new element is always inserted at the Rear position.

1. Steps: Create a new node dynamically and insert value into it.
2. Check if front==NULL, if it is true then front = rear = (newly created node)
3. If it is false then rear=(newly created node) and rear node always contains the
address of the front node.

deQueue() - This function is used to delete an element from the circular queue. In a queue, the
element is always deleted from the front position.

1. Check whether the queue is empty or not means front == NULL.


2. If it is empty then the display Queue is empty. If queue is not empty then step 3
3. Check if (front==rear) if it is true then set front = rear = NULL else move the
front forward in queue, update the address of front in rear node and return the
element.

Double Ended Queue (DEQUE)

• It is a special queue like data structure that supports insertion and deletion at
both the front and the rear of the queue.
• Such an extension of a queue is called a double-ended queue, or deque,
which is usually pronounced "deck" to avoid confusion with the dequeue
method of the regular queue, which is pronounced like the abbreviation
"D.Q."
• It is also often called a head-tail linked list.
PRIORITY QUEUE

A priority queue is a collection of elements that each element has been


assigned a priority and such that order in which elements are deleted and
processed comes from the following riles:

– An element of higher priority is processed before any element of


lower priority.
– Two element with the same priority are processed according to the
order in which they were added to the queue.
Module 3

Singly Linked List

# include <stdio.h>
# include <conio.h>
# include <stdlib.h>

struct node
{
int data;
struct node *next;
};
typedef struct node NODE;
NODE *start = NULL;
int menu()
{
int ch;
system("cls");
printf("\n 1.Create a list ");
printf("\n--------------------------");
printf("\n 2.Insert a node at beginning ");
printf("\n 3.Insert a node at end");
printf("\n--------------------------");
printf("\n 4.Delete a node from beginning");
printf("\n 5.Delete a node from Last");
printf("\n--------------------------");
printf("\n 6.Displaying the list");
printf("\n--------------------------");
printf("\n 7.Exit ");
printf("\n\n Enter your choice: ");
scanf("%d",&ch);
return ch;
}

NODE* getnode()
{
NODE * newnode;
newnode = (NODE *) malloc(sizeof(NODE));
printf("\n Enter data: ");
scanf("%d", &newnode -> data);
newnode -> next = NULL;
return newnode;
}

void createlist (int n)


{
int i;
NODE *newnode, *temp;
for(i = 0; i < n; i++)
{
newnode = getnode();

if(start == NULL)
{
start = newnode;
}
else
{
temp = start;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;
}
}
}
void display()
{
NODE *temp;
temp = start;
printf("\n The contents of List (Left to Right): \n");
if(start == NULL)
{
printf("\n Empty List");
return;
}
else
{
while(temp != NULL)
{
printf("%d-->", temp -> data);
temp = temp -> next;
}
}
}

void insert_at_beg()
{
NODE *newnode;
newnode = getnode();
if(start == NULL)
{
start = newnode;
}
else
{
newnode -> next = start;
start = newnode;
}
}

void insert_at_end()
{
NODE *newnode, *temp;
newnode = getnode();
if(start == NULL)
{
start = newnode;
}
else
{
temp = start;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;
}
}

void delete_at_beg()
{
NODE *temp;
if(start == NULL)
{
printf("\n No nodes are exist..");
return ;
}
else
{
temp = start;
start = temp -> next;
printf("\n Node deleted %d", temp->data);
free(temp);
}
}

void delete_at_last()
{
NODE *temp, *prev;
if(start == NULL)
{
printf("\n Empty List..");
return ;
}
else
{
temp = start;
prev = start;
while(temp -> next != NULL)
{
prev = temp;
temp = temp -> next;
}
prev -> next = NULL;
printf("\n Node deleted %d", temp->data);
free(temp);
}
}

int main ()
{
int ch, n;
while(1)
{
ch = menu();
switch(ch)
{
case 1:
if(start == NULL)
{
printf("\n Number of nodes you want to create: ");
scanf("%d", &n);
createlist(n);
printf("\n List created..");
}

else
printf("\n List is already created..");
break;
case 2:
insert_at_beg();
break;
case 3:
insert_at_end();
break;
case 4:
delete_at_beg();
break;
case 5:
delete_at_last();
break;
case 6:
display();
break;
case 7:
exit(0);
}
getch();
}
}

Doubly linked list is a complex type of linked list in which a node contains a pointer to the previous as
well as the next node in the sequence. Therefore, in a doubly linked list, a node consists of three parts:
node data, pointer to the next node in sequence (next pointer) , pointer to the previous node (previous
pointer). A sample node in a doubly linked list is shown in the figure.

Source Code
#include <stdio.h>
#include <stdlib.h>

struct dlinklist
{
struct dlinklist *left;
int data;
struct dlinklist *right;
};
typedef struct dlinklist NODE;

NODE *start = NULL;

NODE* getnode()
{
NODE * newnode;
newnode = (NODE *) malloc(sizeof(NODE));
printf("\n Enter data: ");
scanf("%d", &newnode -> data);
newnode -> left = NULL;
newnode -> right = NULL;
return newnode;
}

int menu()
{
int ch;
system("clear");
printf("\n 1.Create a list ");
printf("\n------------------------------");
printf("\n 2. Insert a node at beginning ");
printf("\n 3. Insert a node at end");
printf("\n------------------------------");
printf("\n 4. Delete a node from beginning");
printf("\n 5. Delete a node from Last");
printf("\n------------------------------");
printf("\n 6. Traverse the list from Left to Right ");
printf("\n 7. Traverse the list from Right to Left ");
printf("\n------------------------------");
printf("\n 8.Exit");
printf("\n\n Enter your choice: ");
scanf("%d", &ch);
return ch;
}

void createlist(int n)
{
int i;
NODE *newnode, *temp;
for(i = 0; i < n; i++)
{
newnode = getnode();
if(start == NULL)
start = newnode;
else
{
temp = start;
while(temp -> right)
temp = temp -> right;
temp -> right = newnode;
newnode -> left = temp;
}
}
}

void display_left_to_right()
{
NODE *temp;
temp = start;
printf("\n The contents of List: ");
if(start == NULL )
printf("\n Empty List");
else
{
while(temp != NULL)
{
printf("\t %d ", temp -> data);
temp = temp -> right;
}
}
}

void display_right_to_left()
{
NODE *temp;
temp = start;
printf("\n The contents of List: ");
if(start == NULL)
printf("\n Empty List");
else
{
while(temp -> right != NULL)
temp = temp -> right;
}
while(temp != NULL)
{
printf("\t%d", temp -> data);
temp = temp -> left;
}
}

void dll_insert_beg()
{
NODE *newnode;
newnode = getnode();
if(start == NULL)
start = newnode;
else
{
newnode -> right = start;
start -> left = newnode;
start = newnode;
}
}

void dll_insert_end()
{
NODE *newnode, *temp;
newnode = getnode();
if(start == NULL)
start = newnode;
else
{
temp = start;
while(temp -> right != NULL)
temp = temp -> right;
temp -> right = newnode;
newnode -> left = temp;
}
}

void dll_delete_beg()
{
NODE *temp;
if(start == NULL)
{
printf("\n Empty list");
getchar();
return ;
}
else
{
temp = start;
start = start -> right;
start -> left = NULL;
free(temp);
}
}

void dll_delete_last()
{
NODE *temp;
if(start == NULL)
{
printf("\n Empty list");
getchar();
return ;
}
else
{
temp = start;
while(temp -> right != NULL)
temp = temp -> right;
temp -> left -> right = NULL;
free(temp);
temp = NULL;
}
}

int main()
{
int ch,n;
//system("sys");
while(1)
{
ch = menu();
switch( ch)
{
case 1 :
printf("\n Enter Number of nodes to create: ");
scanf("%d", &n);
createlist(n);
printf("\n List created..");
break;
case 2 :
dll_insert_beg();
break;
case 3 :
dll_insert_end();
break;
case 4 :
dll_delete_beg();
break;
case 5 :
dll_delete_last();
break;
case 6 :
display_left_to_right();
break;
case 7 :
display_right_to_left();
break;
case 8:
exit(0);
}
getchar();
}
}

Output
In a circular singly linked list, the last node of the list contains a pointer to the first node of the list. We can
have circular singly linked list as well as circular doubly linked list.

We traverse a circular singly linked list until we reach the same node where we started. The circular singly
liked list has no beginning and no ending. There is no null value present in the next part of any of the nodes.

The following image shows a circular singly linked list.

Circular Linked List Write a C Program to perform following operations on Circular Linked List
ADT :
i. Create ii. Insert iii. Delete. iv. Display

Source Code

#include <stdio.h>
#include <stdlib.h>

struct clinklist
{
struct clinklist *next;
int data;

};
typedef struct clinklist NODE;

NODE *start = NULL;

NODE* getnode()
{
NODE * newnode;
newnode = (NODE *) malloc(sizeof(NODE));
printf("\n Enter data: ");
scanf("%d", &newnode -> data);
newnode -> next = NULL;
return newnode;
}

int menu()
{
int ch;
system("clear");
printf("\n 1. Create a list ");
printf("\n\n--------------------------");
printf("\n 2. Insert a node at beginning ");
printf("\n 3. Insert a node at end");
printf("\n\n--------------------------");
printf("\n 4. Delete a node from beginning");
printf("\n 5. Delete a node from Last");
printf("\n\n--------------------------");
printf("\n 6. Display the list");
printf("\n 7. Exit");
printf("\n\n--------------------------");
printf("\n Enter your choice: ");
scanf("%d", &ch);
return ch;
}

void createlist(int n)
{
int i;
NODE *newnode,*temp;

for(i = 0; i < n ; i++)


{
newnode = getnode();
if(start == NULL)
{
start = newnode;
}
else
{
temp = start;
while(temp -> next != NULL)
temp = temp -> next;
temp -> next = newnode;
}
}
newnode ->next = start; /* last node is pointing to starting node */
}

void display()
{
NODE *temp;
temp = start;
printf("\n The contents of List (Left to Right): ");
if(start == NULL )
printf("\n Empty List");
else
{
do
{
printf("\t %d ", temp -> data);
temp = temp -> next;
} while(temp != start);
//printf(" X ");
}
}

void cll_insert_beg()
{
NODE *newnode, *last;
newnode = getnode();
if(start == NULL)
{
start = newnode;
newnode -> next = start;
}

else
{
last = start;
while(last -> next != start)
last= last -> next;
newnode -> next = start;
start = newnode;
last -> next = start;
}
printf("\n Node inserted at beginning..");

void cll_insert_end()
{
NODE *newnode, *temp;
newnode = getnode();
if(start == NULL )
{
start = newnode;
newnode -> next = start;
}
else
{
temp = start;
while(temp -> next != start)
temp = temp -> next;
temp -> next = newnode;
newnode -> next = start;
}
printf("\n Node inserted at end..");

void cll_delete_beg()
{
NODE *temp, *last;
if(start == NULL)
{
printf("\n No nodes exist..");
getchar();
return ;
}
else
{
last = temp = start;
while(last -> next != start)
last= last -> next;
start = start -> next;
last -> next = start;
free(temp);
printf("\n Node deleted..");

}
}

void cll_delete_last()
{
NODE *temp,*prev;

if(start == NULL)
{
printf("\n No nodes exist..");
getchar();
return ;
}
else
{
temp = start;
prev = start;

while(temp -> next != start)


{
prev = temp;
temp = temp -> next;
}
prev -> next = start;
free(temp);
}
}

int main()
{
int result;
int ch, n;
//system ("sys");
while(1)
{
ch = menu();
switch(ch)
{
case 1 :
if(start == NULL)
{
printf("\n Enter Number of nodes to create: ");
scanf("%d", &n);
createlist(n);
printf("\nList created..");
}
else
printf("\n List is already Exist..");
break;
case 2 :
cll_insert_beg();
break;
case 3 :
cll_insert_end();
break;
case 4 :
cll_delete_beg();
break;
case 5 :
cll_delete_last();
break;
case 6 :
display();
break;
case 7 :
exit(0);
}
getchar();
}
}

Output:
Basic Tree Concepts
A tree consists of a finite set of elements called ‘nodes’, and a finite set of lines, called
‘branches’, that connect the nodes.
The number of branches associated with a node is the degree of the node.
 When the branch is directed toward a node, it is an indegree branch; when
the branch is directed away from the node, it is an outdegree branch.
 Ex: Indegree of B: 1
Outdegree of B:4
 The sum of indegree and outdegree branches is the degree of the node.
 The indegree of the root is by definition is zero.

Binary trees
• A binary tree is a tree in which no node can have more than two children.
• Each node has an element, a reference to a left child and a reference to a right
child.
Binary Tree Representations

A binary tree data structure is represented using two methods. Those methods are as
follows...
1. Array Representation
2. Linked List Representation
Module 4:
Module 5:
Implement Binary Search Tree using Linked List

Explanation: A binary search tree (BST), also known as an ordered binary tree, is a node -based
data structure in which each node has no more than two child nodes. Each child must either be a
leaf node or the root of another binary search tree. The left sub -tree contains only nodes with
value less than the parent node; the right sub-tree contains only nodes with value greater than or
equal
to the parent node.
The BST data structure is the basis for a number of highly efficient sorting and searching
algorithms, and it can be used to construct more abstract data structures including sets,
multisets, and associative arrays.

Tree Traversal:
Displaying (or) visiting order of nodes in a tree is called as Tree Traversal.
There are three types tree traversals:
1. In - Order Traversal
2. Pre - Order Traversal
3. Post - Order Traversal

Source Code:
#include<stdio.h>
#include<stdlib.h>
struct BST
{
int info;
struct BST *llink,*rlink;
};
typedef struct BST node;
node *create(node *root,int ele)
{
node *temp,*prev,*cur;
temp=(node *)malloc(sizeof(node));
temp->info=ele;
temp->llink=NULL;
temp->rlink=NULL;
if(root==NULL)
return temp;
prev=NULL;
cur=root;
while(cur!=NULL)
{
prev=cur;
if(ele<cur->info)
cur=cur->llink;
else
cur=cur->rlink;
}
if(ele<prev->info)
prev->llink=temp;
else
prev->rlink=temp;
return root;
}

void preorder(node *root)


{
if(root==NULL)
return;
printf("%d ",root->info);
preorder(root->llink);
preorder(root->rlink);
}
void inorder(node *root)
{
if(root==NULL)
return;
inorder(root->llink);
printf("%d ",root->info);
inorder(root->rlink);
}

void postorder(node *root)


{
if(root==NULL)
return;
postorder(root->llink);
postorder(root->rlink);
printf("%d ",root->info);
}
int main()
{
node *root=NULL;
int ch,ele;
while(1)
{
printf("\n 1: Create 2: Preorder 3:Inorder 4: Postorder 5:exit:");
printf("\n Enter your choice:");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\n Enter the element to be inserted:");
scanf("%d",&ele);
root=create(root,ele);
break;
case 2:
preorder(root);
break;
case 3:
inorder(root);
break;
case 4:
postorder(root);
break;
case 5:
exit(0);
}
}
getch();
return 0;
}

Output:
Outline the Knuth-Morris-Pratt Algorithm for the given text and pattern using LPS table.
Text: ABC ABCDAB ABCDABCDABDE
Pattern: ABCDAB
Sample Question Bank for End-Sem Examination
Sub: Data Structure
Module 1
1. What do you mean by ADT? Add the following operation to the Natural Number
ADT: Predecessor, IsGreater, Multiply, Divide.
2. Write an algorithm to perform binary search using iteration and recursion.
3. Write an algorithm to perform bubble sort.
4. Write an algorithm to perform linear search.
5. Write a short note on Asymptotic notation.
6. Explain Linear Queue ADT with respect to the following operations: Insert, Delete,
Isempty, Isfull.
7. What do you mean by Data Structure? Explain basic operations performed on a data
structure.
8. Distinguish between linear and non-linear data structures. Give some applications of
data structure.
9. Show that the following statements are correct
a)5n2-6n=ϴ(n2) b) 2n2+nlogn= ϴ(n2)
10. Write an algorithm to perform Selection sort.

Module 2
1. Write a Program to implement Stack using array.
2. Compare Stacks and Queues with respect to Insert and Delete operations taking an
example.
3. Write an algorithm to insert a node p at the beginning, end and after a certain node of
a linked list.
4. Write an algorithm to count the number of nodes in a Linked list.
5. Implement a stack using linked list. Show both the PUSH and POP operations.
6. Write an algorithm to convert the given expression from infix to postfix. Trace the
same for: (a-b)/(c*d)+e
7. Evaluate the postfix expression using stack: 4 2 + 3 5 1 - * +
8. What is disadvantage of linked list over array? What is double linked list?
9. Transform the following infix expressions into their equivalent postfix expressions
i). A*(B+D)/F-F*(G+H/K)
ii). A^B*C+D/A/(E+F)
10. Write an algorithm and function to insert into a circular Queue.
11. What is the advantage of circular queue over queue? Implement Queue using array.
12. Illustrate with a suitable example to discuss the advantages of doubly linked list over
singly linked list. Write C function that will insert a given integer value into an
ordered doubly linked list at a given position.

Module 3
1. Compare the representation of Dictionaries with Arrays and Lists.
2. Explain the operations in Dictionaries.
3. Explain different Hash methods with suitable example.
4. Show the resulting table for given input {3417, 3132, 7122, 5199, 5344, 6796, and
1893} and a hash function h (n) = x mod 10.

153
Hyderabad Institute of Technology and Management

5. What is collision in hashing? Explain various collision resolution techniques along


with their advantages and disadvantages using suitable example?
6. Create a hashing table for the following hashing keys and hashing algorithm:
hashkey+12 mod 8 for the values 12345, 04187, 34237, 23423, 00324, 23448.
7. Explain Liner probing and Quadratic Probing with example.
8. Insert the following keys into the hash table with m=13 using double hashing
technique: 126,75,37,56,29,152,35,99
9. How chaining helps to resolve collision -Explain with an example.
10. Explain Priority Queue with a suitable example.
11. Use Quadratic Probing to insert the list of elements into the hash table for the
sequence of keys as 50, 700, 76, 85, 92, 73, 101 (Size of Hash table is 7).

Module 4
1. Define the following with suitable example: Binary Tree, Complete Binary Tree.
2. Demonstrate how binary tree inorder, preorder and post order travels will help to
obtain the expression in infix, prefix and postfix notations.
3. Construct a Binary search Tree with the help of following Postorder traversal: A I H
G F N Y Z Q L.
4. Draw the steps required to perform a single right rotation, single left rotation, double
RL rotation and double LR rotation in an AVL Tree.
5. Construct an AVL tree with the following keys using the various rotations: 6, 7, 8,
9, 10, 12, 2, 4, 5, 1.
6. Write a short note on Red-Black Tree.
7. Write short note on Splay Tree.
8. Give inorder, preorder and postorder traversal of the following tree.

9. Write an algorithm to search a node into a binary search tree.


10. Write an algorithm to get inorder, preorder and postorder traversal of a binary tree.
11. Consider the following specification of a graph G, V(G)={1,2,3,4}
E(G)={(1,2),(1,3),(3,3),(3,4),(4,1)}
a). Draw a picture of the undirected graph.
b). Give its Adjacency Matrix.
c). Give its Adjacency List.
12. Find adjacency matrix and adjacency list from the following graph:

13. Write pseudocode for BFS and DFS Graph Traversal.

154
Hyderabad Institute of Technology and Management

14. What are the basic differences between Tree and Graph? Give BFS for the
following graph considering starting vertex A.

15. Differentiate BFS and DFS. Give DFS for the following graph considering starting
vertex 0.

16. Write down the function to perform DFS and BFS graph traversal.

Module 5
1. What are the advantages and disadvantages of Merge Sort? Illustrate Merge Sort with
the following data:
78,23,45,8,32,36,5,90,11,15,80.
2. Illustrate bubble sort using the following data: 20,35,40,100,3,10,15.
3. Explain the implementation of Quick Sort with a suitable example.
4. Write a program to implement Insertion Sort.
5. What is a Heap? Build a Max-heap from the following values: 3,5,7,2,1,9,12,7,21.
6. What is a Heap? Sort the following array using Heap Sort Method: 4, 1, 6, 8, 9, 2,
3.
7. What do you mean by pattern matching? Describe Broute-Force Pattern
Matching Algorithm with a suitable example.
8. Find the following Pattern from a string given below using Boyer-Moore Pattern
Matching Algorithm.
String: “A Pattern Matching Algorithm”
Pattern: “rithm”
9. Find the following Pattern from a string given below using KMP Pattern
Matching Algorithm.
String: “aaabcaaacaaaedaaad”
Pattern: “aaad”
10. What do you mean by Trie Data Structure? Make one Trie using the following
strings: bell, bear, bore, bat, ball, stop, stock, and stack.
11. Explain Standard tries with a suitable example.
12. What do you mean by suffix tries? How suffix tries help in pattern matching
show with an example?
13. Discuss about minimum heap and maximum heap for the following set of values 3, 9,
2, 1, 4, 5. And also explain the insertion of element 7 and deletion of an element 3
from the heap.

155
Model Question Bank
PART-A :( 5 x 2 marks = 10)
1a) Differentiate BFS and DFS graph traversal algorithms. [2]
b) Explain the concept of ‘Overflow’ condition on stack. [2]
c) Identify the line no which has a logical error in the selection sort code when [2]
arranging it in ascending order and correct it.
Line No 1: for (i=0; i < n-1; i++)
Line No 2: {
Line No 3: min=i;
Line No 4: for (j=i; j <n; j++)
Line No 5: {
Line No 6: if(a[j]<a[min])
Line No 7: min=i;
Line No 8: }
Line No 9: t=a[min];
Line No 10: a[min]=a[i];
Line No 11: a[i]=t;
Line No 12: }

d) Find all possible prefix and suffix from the string “HITAM”. [2]
e) What are the differences between Tree and Graph? [2]

PART-B: (5 x 10 marks = 50)


2) a) Add the following operation to the Natural Number ADT: [5+5]
Predecessor, IsGreater, Multiply, Divide
b) Write a short note on Asymptotic notation.
(OR)
3) a) Write an algorithm to perform binary search using iteration and recursion. [5+5]
b) Show that the following statements are correct
i)5n2-6n=ϴ(n2) b) 2n2+nlogn= ϴ(n2)
4) a) Compare Stacks and Queues with respect to Insert and Delete operations [5+5]
taking an example.
b) Write an algorithm to convert the given expression from infix to postfix.
Trace the same for: (a-b)/(c*d)+e
(OR)
5) a) What are the advantages and disadvantages of a linked list over an array? [3+4+3]
b) Write an algorithm to count the number of nodes in a Linked list.
c) Explain Doubly Linked List using a example diagram.

6) a) Explain Priority Queue with a suitable example. [5+5]


b) Explain different operations in Dictionary.

(OR)
7) a) Show the resulting table for given input {3417, 3132, 7122, 5199, 5344, [5+5]
6796, and 1893} and a hash function h (x) = x mod 10 and use linear probing
as a collision resolution technique.
b) How chaining helps to resolve collision using chaining method-Explain with
an example.
8) a) Consider the following specification of a graph G, V(G)={1,2,3,4} [5+5]
E(G)={(1,2),(1,3),(3,2),(3,4),(4,1)}
i). Draw a picture of the undirected graph.
ii). Give its Adjacency Matrix.
iii). Give its Adjacency List.
b) Give BFS and DFS for the following graph considering starting vertex 0.

(OR)
9) a) Give inorder, preorder and postorder traversal of the following tree. [5+5]

b) Construct an AVL tree with the following keys using the various rotations:
6, 7, 8, 9, 10, 12, 2, 4, 5, 1
10) a) What is a Heap? Build a Max-heap from the following values: [5+5]
3,5,7,2,1,9,12,7,21.
b) Write a program to implement quick sort.

(OR)
11) a) What do you mean by Trie Data Structure? Make one Trie using the [5+5]
following strings: bell, bear, bore, bat, ball, stop, stock, and stack.
b) What do you mean by suffix tries? How suffix tries help in pattern matching
show with an example?

You might also like