Data Structures with Algorithmic Analysis (study material)
Data Structures with Algorithmic Analysis (study material)
Analysis
III Sem B.E ECE ‘A’ (2023 - 2027 Batch)
Academic Year 2024 - 2025 (Odd Semester)
7
Course Outcomes
At the end of the course, the students will be able to
9
UNIT I ALGORITHM ANALYSIS AND LIST DATA
STRUCTURES
Definition of an Algorithm - Running Time Calculations -
Algorithm Complexity : Time and Space – Asymptotic
notation. List ADT: array based & linked list based
implementation - singly linked lists - circularly linked lists
- doubly linked lists - Polynomial Addition using lists.
10
UNIT II -QUEUE AND STACK DATA STRUCTURES
11
UNIT III - TREE DATA STRUCTURES
12
UNIT IV - DISJOINT SET AND GRAPH
13
UNIT V - HASHING, SORTING ALGORITHMS AND CASE
STUDY
15
1.C Program to find the product of two numbers
#include<stdio.h>
int main(){
int x,y,z;
scanf("%d %d",&x,&y);
z=x*y;
} 17
//3.C Program to find the product of two numbers
using structures.
#include <stdio.h>
typedef struct {
int n1;
int n2;
} product;
int main() {
product calc;
int result;
printf("Enter the first number: ");
scanf("%d", &calc.n1);
printf("Enter the second number: ");
scanf("%d", &calc.n2);
result = calc.n1*calc.n2;
printf("The product of %d and %d is %d.\n", calc.n1, calc.n2, result);
Code Courtesy:
return 0; Sri Mahalakshmi V
} II ECE A 18
//4. C Program to find the product of two numbers using
functions inside structures.
#include <stdio.h>
typedef struct {
int n1;
int n2;
int pro(int x,int y){ //C lang. will not support fun. in struct
return x*y;
}
} product; This program will not
int main() {
product calc; work. Since, the
int result;
function inside
printf("Enter the first number: ");
scanf("%d", &calc.n1);
structure is not
printf("Enter the second number: ");
scanf("%d", &calc.n2);
supported in C
result = calc.pro(calc.n1,calc.n2);
printf("The product of %d and %d is %d.\n", calc.n1, calc.n2, result);
return 0; language. 19
//5) Write a C Program to find the product of two numbers
using pointer variables, functions and structures
#include<stdio.h>
#include<malloc.h>
struct product{
int num1;
int num2;
};
int compute(struct product *calc) {
return calc->num1 * calc->num2;
}
int main() {
struct product *ptrCalc;
//product *ptrCalc = &calc;
ptrCalc = (struct product*) malloc(sizeof(struct product));
int result;
printf("Enter the first number: ");
scanf("%d", &ptrCalc->num1);
printf("Enter the second number: ");
scanf("%d", &ptrCalc->num2); Code Courtesy:
result = compute(ptrCalc); Sri Mahalakshmi V
printf("The product of %d and %d is %d.\n", ptrCalc->num1, ptrCalc->num2, result);
II ECE A
return 0;
20
}
//6.C Program to find the product of two numbers using
functions and returning the structure to main function
#include <stdio.h>
typedef struct {
int num1;
int num2;
int pro;
} product;
product getproduct(int num1, int num2) {
product calc;
calc.num1=num1;
calc.num2=num2;
calc.pro = num1 * num2;
return calc;
}
int main() {
int number1, number2;
printf("Enter the first number: ");
scanf("%d", &number1);
printf("Enter the second number: ");
scanf("%d", &number2); Code Courtesy:
product result = getproduct(number1, number2); Sri Mahalakshmi V
II ECE A
printf("The product of %d and %d is %d.\n", result.num1, result.num2, result.pro);
return 0;
} 21
//6.1.C Program to find the product of two numbers using pointer
variables, functions and returning the structure to main function
#include <stdio.h>
#include <malloc.h>
struct product{
int num1;
int num2;
int pro;
};
struct product* getproduct(int n1, int n2) {
struct product *calc=(struct product*) malloc(sizeof(struct product));
calc->num1=n1;
calc->num2=n2;
calc->pro = calc->num1 * calc->num2;
return calc;
}
int main() {
int number1, number2;
struct product *result;
printf("Enter the first number: ");
scanf("%d", &number1);
printf("Enter the second number: ");
scanf("%d", &number2);
result = getproduct(number1, number2);
printf("The product of %d and %d is %d:\n", result->num1, result->num2, result->pro);
return 0;
} 22
C++ Programming
7) Write a C++ Program to find the product of two numbers.
10) Write a C++ Program to find the product of two numbers using
function inside a structure.
11) Write an OOP in C++ to find the product of two numbers (without
data hiding/encapsulation)
12) Write an OOP in C++ to find the product of two numbers (with data
hiding/encapsulation) 23
Cin & Cout Objects and insertion &
extraction operators
<< - Insertion Operator
>> - Extraction Operator
24
//7.C++ Program to find the product of two numbers
31
//Write an OOP in C++ to find the sum and
average of N numbers in an array.
#include<iostream>
using namespace std;
class Average{
private:
int a[10],n,sum;
float avg;
public:
void getdata(){
cout<<"\nEnter no.
of data:";
cin>>n; cout<<"\
nEnter "<<n<<" data";
for(int i=0;i<n;i++)
cin>>a[i];
}
int findsum(){
sum=0;
for(int i=0;i<n;i++)
sum+=a[i];
return sum;
}
float findavg(){
avg=sum/n;
return avg;
}
};
int main(){
Average a; 32
a.getdata();
//Write an OOP in C++ to find the sum and average of N numbers in an array.
//Write member functions outside the class
#include<iostream>
using namespace std; float Average::findavg(){
class Average{
private: avg=sum/n;
int a[10],n,sum; return
float avg; avg;
public: }
void getdata(); int main(){
int findsum(); Average a;
float findavg(); a.getdata();
}; cout<<"\nSum:"<<a.findsum();
cout<<"\nAvg:"<<a.findavg();
void Average::getdata(){ return 0;
cout<<"\nEnter }
no. of data:";
cin>>n;
cout<<"\nEnter "<<n<<" data";
for(int
i=0;i<n;i++)
cin>>a[i];
}
int Average::findsum(){
sum=0;
for(int
i=0;i<n;i++) 33
2. OOP in C++ to compute the area of square, circle, rectangle
and triangle.(Homework - 31/07/2024)
#include <iostream> float tri() {
using namespace std; return 0.5f * l2 * h;
class Area { }
private: };
int r, l1, b1, a, l2, h;
public: int main() {
void getData() { Area calc;
cout << "Enter the following inputs in order:\n"; int res1, res3;
cout << "Radius of the circle:\n"; float res2, res4;
cin >> r; calc.getData();
cout << "Length and breadth of a rectangle:\n"; res1 = calc.sq();
cin >> l1 >> b1; res2 = calc.circ();
cout << "Side of a square:\n"; res3 = calc.rect();
cin >> a; res4 = calc.tri();
cout << "Length and height of a triangle:\n"; cout << "The area of a square is: " << res1 << endl;
cin >> l2 >> h; cout << "The area of a circle is: " << res2 << endl;
} cout << "The area of a rectangle is: " << res3 << endl;
int sq() { cout << "The area of a triangle is: " << res4 << endl;
return a * a; return 0;
} }
float circ() { Code Courtesy:
return 3.14f * r * r; Fahmitha Sherin I
} II ECE A
int rect() {
return l1 * b1; 34
}
Homework - 01/08/2024
1. Write an OOP in C++ to find the maximum
number of two numbers
2. Write an OOP in C++ to check if the entered
string is a palindrome.
35
1. OOP in C++ to find the maximum number of two numbers
(Homework - 01/08/2024)
#include<iostream>
using namespace std;
class Maximum{
private:
int x,y;
public:
void getdata();
int findmaximum();
};
void Maximum::getdata(){
cout<<"Enter the value of x:";
cin>>x;
cout<<"Enter the value of y:";
cin>>y;
}
int Maximum::findmaximum(){
if(x>y)
return x;
else
return y;
}
Code Courtesy:
int main(){
Maximum a; Aravind Kumar V
a.getdata(); II ECE A
cout<<"\nThe maximum value is:"<<a.findmaximum(); 36
return 0;
2. OOP in C++ to check if the entered string is a palindrome.
(Homework - 01/08/2024)
#include <iostream>
#include <cstring> int main() {
using namespace std; Palindrome c;
class Palindrome { string result;
private: c.getData();
char a[100]; result = c.isPalindrome();
public: cout << result << endl;
void getData() { return 0;
cout << "Enter the string: "; }
cin >> a;
}
string isPalindrome() {
int length = strlen(a);
char reversed[100];
for (int i = 0; i < length; i++) {
reversed[i] = a[length - i - 1];
}
reversed[length] = '\0';
if (strcmp(a, reversed) == 0)
return "The given string is a palindrome.";
else Code Courtesy:
return "The given string is not a palindrome."; Deebisha D
} II ECE A
};
37
Why Study Data Structures?
“
“Bad programmers worry about the
code. Good programmers worry
about data structures and their
relationships.” -Linus Torvalds
38
Data Structures Handbook
Android App:
https://play.google.com/store/a
pps/details?id=com.bashoverfl
ow.datastructures
Web Link:
https://www.thedshandbook.
com/
39
Apps
40
UNIT - I
ALGORITHM ANALYSIS
AND LIST DATA
STRUCTURES
41
UNIT I - ALGORITHM ANALYSIS AND LIST DATA
STRUCTURES
● Definition of an Algorithm
● Running Time Calculations
● Algorithm Complexity
○ Asymptotic notation
○ Time and Space
● Data Structures
● List ADT
○ Array based
○ Linked list based implementation
■ Singly linked lists
■ Circularly linked lists
■ Doubly linked lists
● Polynomial Addition using lists. 42
Introduction to Data Structures
43
UNIT I - ALGORITHM ANALYSIS AND LIST DATA
STRUCTURES
● Definition of an Algorithm
● Running Time Calculations
● Algorithm Complexity
○ Asymptotic notation
○ Time and Space
● Data Structures
● List ADT
○ Array based
○ Linked list based implementation
■ Singly linked lists
■ Circularly linked lists
■ Doubly linked lists
● Polynomial Addition using lists. 44
Introduction to Data Structures
Data:
Sequence of bits, bytes, text, images, videos etc.,
Data Structure:
It provides a systematic way of organizing,
accessing and processing of data, present in the
computer memory
Information:
If we arrange data in an appropriate sequence,
then it forms a structure and gives us a meaning.
It is called as information. 45
Introduction to Data Structures
Algorithm:
● Outlines the essence of computation
procedures through step by step
instructions.
● In the context of data structure,
algorithms are:
○ Meant to give proper structure to
the data.
○ Extract information from the data
Program: 46
What is Data Structures?
● Data Structure is the representation of
relationship that exists between
individual elements of data to carry out
certain operations / tasks.
● Data Structure considers not only the
organization of the elements, but also stores
the relationship between those elements.
47
What is Data Structures?
Data Structure = Data + Organizing, accessing
and processing of data (through algorithms)
Data Structure = Data + Establish relationship
between data (through algorithms)
Data Structure = Organized data + Allowed set
of operations on those data (Provided by the
algorithm)
48
Why Data Structures?
● Study of how data needs to be stored in
computer, so that operations on the data can
be implemented efficiently.
● Data structures are highly important, when we
have large amount of data.
● Conceptual and concrete means to organize
data for efficient storage and retrieval /
manipulation.
49
Types of Data Structures
50
Types of Data Structures
● Primary / Primitive/ Built-in Data Structure
○ Basic constants / Data types (int, char, float,
double)
○ Pointers
● Secondary /Non- Primitive/ User defined
Data Structure
○ Static (Arrays, Structures)
○ Dynamic
■ Linear (Dynamic arrays, list, stack, queue)
■ Non-Linear (Tree, Graph, Disjoint set,
Hashtable)
51
Types of Data Structures
Static Dynamic
Basic constants /
Pointers
Data types
57
Abstract Data Type (ADT)
● ADTs are more promising way of looking at data structures.
They are user defined data types. All data structures are
built on top of ADTs.
● From the perspective of data structures, ADTs focuses on
what it does on does on data and it ignores how the tasks
are done / implemented.
struct student {
class student {
public:
};
void getdata(){}
};
int main(){
int main(){ interface
struct student s;
student s;
implementatio getdata();
s.getdata(); n
sort();
s.sort();
} 59
Benefits of Abstract Data Type (ADT)
1) Traversal
2) Insertion
3) Search
4) Delete
5) Sorting
6) Merging
7) etc.,
65
Homework - 03/08/2024
1. Write an OOP in C++ to check if the entered
data is an character, number or a special
character.
2. Write an OOP in C++ to find the volume of
cube, and sphere.
3. Write an OOP in C++ to get and print the
specifications of your smartphone.
66
1. OOP in C++ to check if the entered data is an character,
number or a special character (Homework - 03/08/2024 )
#include <iostream>
#include <cctype>
using namespace std;
class Detect {
private:
char x;
public:
void getData() {
cout << "Enter a single character: ";
cin >> x;
}
void detectChar() {
if (isdigit(x))
cout << "The entered data is a number" << endl;
else if (isalpha(x))
cout << "The entered data is a character" << endl;
else if (ispunct(x))
cout << "The entered data is a special character" << endl;
else
cout << "The entered data is not a valid character" << endl;
}
};
int main() {
Detect t; Code Courtesy:
t.getData(); Fahmitha Sherin I
t.detectChar(); II ECE A
return 0;
} 67
2. OOP in C++ to find the volume of cube, and sphere.
(Homework - 03/08/2024)
#include <iostream> int main() {
using namespace std; Vol v;
class Vol { double r1;
private: int r2;
int r, a;
public: v.getData();
void getData() { r1 = v.volSp();
cout << "Enter the radius of a sphere: "; r2 = v.volCube();
cin >> r;
cout << "Enter the side of a cube: "; cout << "The volume of the sphere is: " << r1
cin >> a; cout << "The volume of the cube is: " << r2 <
}
double volSp() { return 0;
double radius = r; }
return (4.0 / 3.0) * 3.14 * radius * radius * radius;
}
int volCube() { Code Courtesy:
return a * a * a; Sri Mahalakshmi V
} II ECE A
};
68
List ADT
69
List ADT
1)General list of n items may be of form A1, A2….An
2)Elements in the list can be int, char, float, structure, or any
combination of any complex data type elements.
3)We can perform set of operations on the list to insert, delete,
print etc.,
4)List is a flexible data structure because, they can grow (insert)
or shrink (delete) based on the demand (data).
5)The elements can be accessed, inserted or deleted at any
position within the list. (for performing these operations, we
need to write algorithms)
70
Implementation of List ADT
Two ways of implementation (writing the
algorithm / program ) is possible
1)Array based implementation
2)Linked list implementation (Pointer
based implementation)
71
List ADT Implementation List ADT Implementation
with Single data Example with Multiple data Example
S.No. Name Brand Model Number
Tracking of Need not keep track (since it We need to keep track of the memory
memory is continuous) location (since it is random)
locations
73
Array based List ADT vs Linked List
Features Array based List ADT Linked List (Pointer based)
Elements Proportional to size of array We can insert elements till the size of
fixed your RAM.
Cost of insertion and Proportional to size of array Independent on the size of the list (low)
deletion of elements (very high)
75
Array based implementation of List ADT
1) Insert
a) Insert at a particular location
b) Insert before / after a particular value
c) Insert at beginning
d) Insert at end etc.,
2) Display Write an OOP in C++ program to implement the given
3) Modify problem statement with separate member functions for
4) Search each algorithm.
5) Delete
a) Based on value
b) Based on location
c) Delete at beginning of list
d) Delete at end etc.,
6) Clear
7) etc., 78
Homework - 9/8/2024
What is the core data structure used for
implementing the following social media
platforms
1) Facebook
2) Twitter
3) LinkedIn
4) Whats App
5) Instagram
6) Google Maps 79
Problem Statement for Data Structure Lab
Search for Smart India Hackathon Example:
Problem Statements class Smartphone {
private:
struct mobile{
https://sih.gov.in/
string Name;
string Brand;
● Watch out for the recent ones and
string Model;
the previous year's problem float price;
statements. long int Number;
● Frame the member variables and } s[max];
member functions (given an public:
example below) for your chosen void create();
problem statement void insert_first();
void insert_last();
void insert_position();
Respond to this with the following void modify();
details void search();
1) Your name void display();
2) Your teammate's name void deletedata();
3) Title of your problem statement void clear(); 80
List Implementation with Single data
Example
0
#define MAX
62
struct node{
int data;
} s[MAX];
int top = -1; //initialize a reference to traverse across the
array based list
MAX-1 81
Algorithm for inserting into List ADT
(Array based)
void insert(int d) {
if(top==MAX-1) {
cout<<“\n Sorry the list is full”;
Initial configuration of the List (Array-based)
return; 0
7
1 2
....
3
....
4 5 6
MAX-1
}
top = -
++top; 1
After insertion of 5 elements in the List (Array-
based)
s[top].data = d; 0
...
1 2
....
3 4 5 6
MAX-1
7 .
} 82
top =
Algorithm for traversing / displaying List
ADT
(Array based)
void display() {
if(top == -1) {
cout<<“\n Sorry the list is empty”;
return;
}
cout<<“\n The contents of the list are:”;
for(int i = 0; i< =top; i++)
cout<<s[i].data<<“- -> ”;
}
83
Homework - 13/08/2024
Use the program in the link to include the following 2
algorithms (use separate member functions for each
algorithm). Send the completed homework in a single file with
all the following 2 algorithms included.
https://classroom.google.com/c/NjkxNzYwNzI0MjYy/m/NzAzOD
Y1OTE3NjYx/details
1. Write an algorithm for returning the minimum element in
the array based list ADT implementation.
2. Write an algorithm for returning themaximum element in
the array based list ADT implementation.
84
element in the array based list ADT
(Homework-13/08/2024)
int Minimum() {
if(top == -1) {
cout<<“\n Sorry the list is empty”;
return -1;
}
int low=s[0].data;
for(int i=0;i<=top;i++){
if(low>s[i].data)
low=s[i].data;
Code Courtesy:
} Hari Prasath M
return low; II ECE A
85
}
element in the array based list ADT
(Homework-13/08/2024)
int Maximum() {
if(top == -1) {
cout<<“\n Sorry the list is empty”;
return -1;
}
int high=s[0].data;
for(int i=0;i<=top;i++){
if(high<s[i].data)
high=s[i].data;
} Code Courtesy:
Hari Prasath M
return high; II ECE A
} 86
Algorithm for deleting data in a List ADT
(Array based)
void deletedata(int d){ Before deletion in a list of 5 elements (Array-
based)4
if(top == -1) { 0 1 2 3 5 6 7
.... .... MAX-1
cout<<"\nSorry the list is empty";
5 8 7 3 9
return;
} top =
for(int i=0;i<top;i++){ 4
}
--top; top = 87
Homework - 14/08/2024
Use the program in the link to include the following 4 algorithms (use
separate member functions for each algorithm). Send the completed
homework in a single file with all the following 4 algorithms included.
https://classroom.google.com/c/NjkxNzYwNzI0MjYy/m/NzAzODY1OTE3
NjYx/details
s[0].data=d;
top++; Code Courtesy:
Subbaiah C
} II ECE A
89
particular position in the array based list ADT
(Homework-14/08/2024)
void insertatparpos(int pos,int d){
if(top == max-1) {
cout<<"Sorry, the list is full";
return ;
}
for(int i=top; i>=pos; i--)
s[i+1]=s[i];
s[pos].data=d;
top++; Code Courtesy:
Vijay S K
} II ECE A
90
the end in the array based list ADT
(Homework-14/08/2024)
void deletelast(){
if(top == -1){
cout<<"Sorry, the list is empty";
return;
}
top--;
}
Code Courtesy:
Subbaiah C
II ECE A
91
position in the array based list ADT
(Homework-14/08/2024)
void deleteatparpos(int pos){
if(top == -1) {
cout<<"Sorry, the list is empty";
return;
}
for(int i=pos;i<=top;i++)
s[i]=s[i+1];
Code Courtesy:
top--; Vijay S K
II ECE A
} 92
Homework - 16/08/2024
Use the program in the link to include the following 4 algorithms (use
separate member functions for each algorithm). Send the completed
homework in a single file with all the following 4 algorithms included.
https://classroom.google.com/c/NjkxNzYwNzI0MjYy/m/NzAzODY1OTE3
NjYx/details
100
Linked list (Pointer based)
implementation of List ADT
103
Disadvantages of Linked List
● No element can be accessed in a random
fashion. All the elements can be only
accessed in a sequential order.
● We need extra storage for holding the
address of the next node / element in the
list.
● Reverse traversing is challenging, unless
you don't have extra pointers.
104
Applications of Linked List
Linked lists are used in many real-world applications.
Being a basic dynamic data structures, linked lists are always used
for the implementation of other popular data structures like
1) Stack
2) Queue
3) Trees
4) Graphs
5) Hash Tables
6) etc.,
105
Types of Linked List
X X
NULL NULL
Pointer Pointer
Head Pointer Tail
Pointer
Singly Circular Linked list
Head Pointer
Doubly Circular Linked list
111
Implementation of Singly Linked list
In a single linked list, each structure (node) contains elements (data) and
pointer (address) to the next structure (node).
NULL
Head Pointer
Pointer
These set of nodes form a linear data structure with each nodes linked to
its successor.
Steps for Implementation of Singly
Linked list
1. Create Node (using structure- self
referencial)
2. Initialize the pointers for the node (head
pointer, traversal pointer, temp pointer)
3. Write algorithms for
a. Insertion of elements (data)
b. Link the nodes
c. Repeat the same process for other algorithms
also.
Creation of nodes in a Singly Linked list
}
Single Linked List based
implementation of List ADT
Problem Statement / Aim /
Objective
To implement the Single Linked list for the List ADT on a set of numbers
(marks of students / set of integers / scores by a individual players in certain number
of innings). Write appropriate (following set of) algorithms for handling the available
data (set of numbers ) and to structure them (Data structure)
1) Insert
a) Insert at a particular location
b) Insert before / after a particular value
c) Insert at beginning
d) Insert at end etc., Write an
OOP in C++ program to implement the given
2) Display problem statement with separate member functions
3) Modify for each algorithm.
4) Search
5) Delete
a) Based on value
b) Based on location
c) Delete at beginning of list
d) Delete at end etc.,
6) Clear
7) etc.,
C++ Program template for implementation
class SingleList{
private:
struct node{
int data; //store the data
struct node *next; //hold the address of next
node
}*head,*p,*temp; //define the pointer variables
public:
SingleList(){ //initialize the pointer variables in the
constructor
head=NULL;
p=NULL;
temp=NULL;
}
//list down all the function prototypes to be used in the
implementation
Node creation for single linked list ADT
struct node{
int data; //store the data
struct node *next; //hold the address of next node
}*head = NULL, *p=NULL, *temp=NULL;
*head - Head pointer, it always points to the first node in the linked
list.
*p - Pointer to traverse from the first node to the last node ( or to
traverse in between the nodes in a linked list)
*temp - Meant for creating new nodes, or for doing temporary
operations in the linked list.
Initially all the pointers are made NULL (means that list is
empty or the list is not created)
Algorithm for inserting into List ADT(Single Linked List)
void insert(int d){
//temp = (struct node*)malloc(sizeof(struct node));
temp = new struct node;
temp->data=d;
temp->next=NULL; During insertion of 1st node
if(head==NULL){ //if the list is empty
During insertion of 2nd node
head = temp;
For insertion from 3rd node
return; onwards
}
p=head; //initialize the first node to ‘p’
while(p->next!=NULL) //traverse till the end of
the list
p=p->next; //gets traversed to the 118
Algorithm for displaying List ADT(Linked List based)
void display(){
if(head==NULL){
cout<<"\nSorry the list is empty";
return;
}
p=head;
while(p!=NULL){ //traverse till the last node in the list
cout<<p->data<<"-->"; //print the data
p=p->next; //gets traversed to the next node in the list
}
}
119
Algorithm for Inserting at the Beginning as the
node in a List ADT(Linked List based)
void insertatbeg(int d){
//temp = (struct node*)malloc(sizeof(struct
node)); Before inserting @ First location as head node
temp = new struct node;
temp->data=d; head
X
temp->next=NULL;
d New node
X
if(head==NULL){ temp
}
head =
temp
temp->next=head;
head=temp; 120
Homework - 20/08/2024
Use the program in the link to include the following 4 algorithms (use
separate member functions for each algorithm). Send the completed
homework in a single file with all the following 4 algorithms included.
https://classroom.google.com/c/NjkxNzYwNzI0MjYy/m/NzA3MjYyNzA4
ODMx/details
p=head; deleted
d X
while(p->data!=d){ head tem
p
p p-
>next
temp->next=p->next;
p >next
delete p;
} 126
Algorithm for delete the first node in a List ADT(Linked
List based)
Before deleting the head node
void deletebeg(){ Node to be
deleted
if(head==NULL){
X
p=head p->next
return; head
X
}
p=head;
head=p->next;
delete p;
} 127
Algorithm for delete the first node in a List ADT(Linked
List based)
void deletebeg(){
if(head==NULL){
cout<<"\nSorry the list is empty";
return;
}
p=head;
head=p->next;
delete p;
} 128
Homework - 22/08/2024
Use the program in the link to include the following 4 algorithms (use
separate member functions for each algorithm). Send the completed
homework in a single file with all the following 4 algorithms included.
https://classroom.google.com/c/NjkxNzYwNzI0MjYy/m/NzA3MjYyNzA4
ODMx/details
void deletelast(){
if(head==NULL){
cout<<"\nSorry the list is empty";
return;
}
p=head;
while(p->next!=NULL){
temp=p;
p=p->next;
}
temp->next = NULL; Code Courtesy:
delete p; Subbaiah C
II ECE A
} 130
2.Algorithm to delete a node based on its position in a single
linked list ADT implementation..(Homework-22/08/2024)
Code Courtesy:
II ECE A
131
3.Algorithm to to insert a node at a particular position in a
single linked list ADT implementation.(Homework-22/08/2024)
void insertparticular(int d, int pos){
int count=0;
if(head==NULL){
cout<<"\nSorry the list is empty";
return;
}
temp=new struct node;
temp->data=element;
p=head;
while(p->next!=NULL && count<pos-1) {
p=p->next;
count++;
}
temp->next=p->next;
p->next=temp; Code Courtesy:
} Steve Johnson Rathinam
G
II ECE A
132
4.Algorithm to clear the contents of a single linked list ADT
implementation.(Homework-22/08/2024)
Code Courtesy:
II ECE A
133
Homework - 23/08/2024
Use the program in the link to include the following 4 algorithms (use
separate member functions for each algorithm). Send the completed
homework in a single file with all the following 4 algorithms included.
https://classroom.google.com/c/NjkxNzYwNzI0MjYy/m/NzA3MjYyNzA4
ODMx/details
Code Courtesy:
II ECE A
135
2.Algorithm to square all the elements in a single linked
list ADT implementation..(Homework-23/08/2024)
void Square(){
if(head==NULL) {
cout<<"List is empty";
return;
}
p=head;
while(p!=NULL) {
p->data=p->data*p->data;
p=p->next; Code Courtesy:
Hari Prasath M
} II ECE A
} 136
3.Algorithm to swap the first and 4th node in a single
linked list ADT implementation.(Homework-23/08/2024)
Code Courtesy:
II ECE A
137
4.Algorithm to remove the nodes with even numbers in a
single linked list ADT implementation.(Homework-23/08/2024)
Code Courtesy:
II ECE A
138
Double Linked List
Implementation of List ADT
139
Implementation of Doubly Linked list
In a double linked list, each structure (node) contains elements (data)
and pointer (address) to the next structure (node) and pointer to
previous structure (node).
X X
NULL NULL
Pointer Pointer
Head Pointer Tail
Pointer
These set of nodes form a linear data structure with each nodes linked
to its successor and predecessor.
Double Linked List based implementation of List
ADT
Problem Statement / Aim /
Objective
To implement the Double Linked list for the List ADT on a set of
numbers (marks of students / set of integers / scores by a individual
players in certain number of innings). Write appropriate (following set of)
algorithms for handling the available data (set of numbers ) and to
structure them (Data structure)
1) Insert
a) Insert at a particular location
b) Insert before / after a particular value
c) Insert at beginning
d) Insert at end etc., Write
an OOP in C++ to implement the given problem
2) Display statement with separate functions for each and every
a) Forward algorithm.
b) Reverse
3) Modify
4) Search
5) Delete
a) Based on value
b) Based on location
c) Delete at beginning of list
d) Delete at end etc.,
Creation of nodes in a Double Linked
list
float cgpa;
struct node *prev;//hold the address of previous node
struct node *next; //hold the address of next node
}
Node creation for Doubly linked list ADT
struct node{
int data; //store the data
struct node *next; //hold the address of next node
struct node *prev; //hold the address of previous node
}*head = NULL, *tail=NULL, *p=NULL, *temp=NULL;
*head - Head pointer, it always points to the first node in the linked list.
*tail - Tail pointer, it always points to the last node in the linked list.
*p - Pointer to traverse from the first node to the last node / last node to first node (
or to traverse in between the nodes in a linked list)
*temp - Meant for creating new nodes, or for doing temporary operations in the
linked list.
Initially all the pointers are made NULL (means that list is empty or the
Algorithm for inserting into a Doubly Linked
List ADT
void displayforward(){
if(head==NULL){
cout<<"\nSorry the list is
empty";
return;
}
p=head;
while(p!=NULL){ //traverse till the last
node in the list
cout<<p->data<<"-->"; //print
the data
p=p->next; //gets traversed to the next 145
Algorithm for displaying reverse in Double Linked List
ADT
void displayreverse(){
if(head==NULL){
cout<<"\nSorry the list is
empty";
return;
}
p=tail;
while(p!=NULL){ //traverse till the first
node in the list
cout<<p->data<<"-->"; //print
the data
p=p->prev; //gets traversed to the prev. 146
Algorithm for deletion based on value in a Double
Linked List ADT
void deletedata(int d){
if(head==NULL){
cout<<"\nSorry the list is empty";
return;
}
p=head;
while(p->data!=d){
temp=p;
p=p->next;
}
temp->next=p->next;
p->next->prev=temp;
delete p;
} 147
Homework - 27/08/2024
Use the program in the link to include the following 5 algorithms (use
separate member functions for each algorithm). Send the completed
homework in a single file with all the following 5 algorithms included.
https://classroom.google.com/c/NjkxNzYwNzI0MjYy/m/NzA4NTM1NjE4Nz
c5/details
1) Write an Algorithm for deletion of a node based on position in a
Double Linked List ADT
2) Write an Algorithm for deleting the first node in a Double Linked List
ADT
3) Write an Algorithm for deleting the last node in a Double Linked List
ADT
4) Write an Algorithm for inserting the first node in a Double Linked List
ADT
148
5) Write an Algorithm for modifying a value in a Double Linked List ADT
1.Algorithm for deletion of a node based on position in a
double linked list ADT implementation.(Homework-27/08/2024)
Code Courtesy:
II ECE A
149
2.Algorithm for deleting the first node in a Double Linked
List ADT.(Homework-27/08/2024)
Code Courtesy:
Hari Prasath M
II ECE A
150
3.Algorithm for deleting the last node in a Double Linked
List ADT (Homework-27/08/2024)
Code Courtesy:
II ECE A
151
4.Algorithm for inserting the first node in a Double Linked
List ADT(Homework-27/08/2024)
Code Courtesy:
II ECE A
152
5.Algorithm for modifying a value in a Double Linked List
ADT (Homework-27/08/2024)
void modify(int old_value, int new_value){
if(head==NULL){
cout<<"Sorry the list is empty";
return;
}
p=head;
while(p!=NULL){
if(p->data==old_value){
p->data=new_value;
return;
}
p=p->next;
Code Courtesy:
} II ECE A
cout<<"Data not found";
} 153
Homework - 28/08/2024
Use the program in the link to include the following 4 algorithms (use
separate member functions for each algorithm). Send the completed
homework in a single file with all the following 4 algorithms included.
https://classroom.google.com/c/NjkxNzYwNzI0MjYy/m/NzA4NTM1NjE4
Nzc5/details
1) Write an Algorithm to swap the first and last nodes in a Double
Linked List ADT
2) Write an Algorithm for deleting the nodes with even numbers in a
Double Linked List ADT
3) Write an Algorithm for find the square of the elements by
traversing from the tail node in a Double Linked List ADT
4) Write an Algorithm for modifying the values divisible by 3 with
100 in a Double Linked List ADT 154
Analysis of Algorithms
155
UNIT I - ALGORITHM ANALYSIS AND LIST DATA
STRUCTURES
● Definition of an Algorithm
● Running Time Calculations
● Algorithm Complexity
○ Asymptotic notation
○ Time and Space
● Data Structures
● List ADT
○ Array based
○ Linked list based implementation
■ Singly linked lists
■ Circularly linked lists
■ Doubly linked lists
● Polynomial Addition using lists. 156
Algorithms
● Outlines the essence of computation procedures
through step by step instructions.
● In the context of data structure, algorithms are meant
to give proper structure to the data.
● Transforms input to output through the computation
procedures.
● An important step is to determine, how many
resources (i.e. in terms of memory, time and
space) are required by the algorithm.
● A best algorithm should consume very minimum
resources.
Properties of Algorithms
1.Finitiness
2.Absence of Ambiguity
3.Definition of sequence
4.Feasibility
5.Input
6.Output
Mathematical preliminaries on analysis.
O(1) Constant
O(log N) Logarithmic
O(N) Linear
O(N2) Quadratic
O(N3) Cubic
O(2N) Exponential
O(N!) Factorial
etc.,
Big Oh (O) Notation
f(n) = O(g(n))
● Where, the function f(n) will not grow faster than the
function g(n)
Big Oh(O) - Upper bound (worst case )
Running Time /
Space
Number of inputs
(n)
164
Big Omega(Ω) Notation
f(n) = Ω(g(n))
● Where, the function f(n) will not go below than the
function g(n)
Big Omega (Ω) - Lower bound (best case)
Running Time /
Space
Number of inputs
(n) 166
Big Theta(𝚯) Notation
f(n) = 𝚯(g(n))
● Where, the function f(n) will not exceed or go below
than the function g(n)
Big Theta (𝚯) - Two-way bound (average case)
Running Time /
Space
Number of inputs
(n)
168
Number of
Run time Complexity of Algorithms
Run-time and space complexity
analysis of algorithm
171
Run-time and space complexity analysis of
algorithm
Find the worst case running time and space of the
following algorithm and analyse the algorithm with Big
Oh(O) implementation.
int sum(int N){
int i,s;
i=0; =>(1 assign) => 1 unit
s=0; =>(1 assign) => 1 unit
for(i=1;i<=N;i++) =>(1 assign, N+1 testing, N increment)
=> 2N+2 units
s+=i; =>(1 add, 1 assign- happens N
times) => 2N units
return s;
}
Ignoring the calling costs and returning functions, we have total
of 4N+4 => So, the function is O(N). Therefore,
worst case run time of the algorithm is O(N).
Space complexity: For storing/processing N elements, N
Worst case run time of looping
statements
What is the worst case run time of this looping statement
for(i=0;i<N;i++)
for(j=0;j<N;j++)
a++;
O(N2) - Since we have two nested loops running NxN times
What is the worst case run time of this looping statement
for(i=0;i<N;i++)
for(j=0;j<N;j++)
for(k=0;k<N;k++)
a++;
177
Homework - 31/08/2024
1)Differentiate Big Oh (O) and Little Oh (o) &
give their mathematical representation
2)Differentiate Big Omega (Ω) and Little Omega
(⍵) & give their mathematical representation
3)Differentiate Big Theta (𝚯) and Little Theta
(𝝷) & give their mathematical representation
4)Analyze the worst-case run-time and space
complexity of the bubble sorting algorithm,
and give its Big Oh representation.
178
Polynomial Manipulation using
Lists
179
Polynomial Manipulation using List ADT
P3 => P1 + P2
while(p1->next || p2->next){
if(p1->next){
p3->pow = p1->pow;
p3->coeff = p1->coeff;
p1 = p1->next;
}
if(p2->next){
p3->pow = p2->pow;
p3->coeff = p2->coeff;
p2 = p2->next;
}
p3->next = (struct node *)malloc(sizeof(struct node));
p3 = p3->next;
p3->next = NULL;
}
}
“
End of Unit - I
188
UNIT - II
189
UNIT II
STACK AND QUEUE DATA STRUCTURES
● Queue ADT
○ Array–based
○ Linked list–based
● Types of Queue
● Applications of queues
● Stack ADT
○ Array–based
○ Linked list–based
● Applications of Stack
○ Balancing Symbols
○ Postfix Expressions
○ Infix to Postfix Conversion
Stack ADT
191
Stack ADT
● It's a derived concept of List,
● Restriction that insertion and deletion can be performed at
only end. (Top of the stack).
● Stacks are also called as Last In First Out (LIFO)
● Top pointer (index) always points to the top most element
of a stack
Operations on Stack
1) PUSH - Equivalent to insert operation
2) POP - Equivalent to delete operation (recently inserted
element)
● Performing PUSH operation when memory is full - is an
193
Implementation of Stack ADT
1) PUSH
2) Display
Write an OOP in C ++ to implement the given problem
3) POP statement with separate functions for each algorithm.
4) ModifyTOP
5) Peek
6) isEmpty
7) isFull
8) Clear
9) etc., 196
Algorithm for PUSH Operation in Stack (Array based)
void PUSH(int d) {
if(top==MAX-1) {
printf(“\n Sorry the Stack is full: Stack
Overflow”);
return;
}
++top;
s[top].data = d;
197
Algorithm for displaying the contents of
array based stack ADT
void display(){
if(top==-1){
printf(“\nSorry stack is empty:Stack
underflow”);
return;
}
for(i=top;i>=0;i- -)
printf(“\n%d”,s[i].data);
}
Algorithm for deletion (POP) from an array based stack
ADT
int POP(){
int x;
if(top==-1){
cout<<"\nSorry Stack Underflow; can't
print";
return -1;
}
x=s[top].data;
--top;
return x; 199
Implementation of Stack ADT
1) PUSH
Write an OOP in C++ to implement the given problem
2) Display statement with separate functions for each algorithm.
3) POP
4) ModifyTOP
5) Peek
6) isEmpty
7) Clear
8) etc., 201
Algorithm for insertion (PUSH) in Linked List based
stack ADT
void PUSH(int d){
temp=new struct node;
temp->data=d;
if(top==NULL){
temp->next=NULL;
top=temp;
return;
}
temp->next=top;
top=temp;
}
202
Algorithm for displaying the contents of Linked List
based Stack ADT
void display(){
if(top==NULL){
cout<<"\nSorry Stack is empty; can't print";
return;
}
p=top;
cout<<"\nThe stack contents are:\n";
while(p!=NULL){
cout<<p->data<<endl;
p=p->next;
}
} 203
Algorithm for deletion (POP) from an Linked-list based
stack ADT
int POP(){
if(top==NULL){
cout<<"\nSorry Stack is empty; can't print";
return -1;
}
p=top;
int x=p->data;
top=top->next;
delete p;
return x;
} 204
Algorithm for deletion (POP) from an Linked-list based
stack ADT (Return whole node)
struct node* POPNode(){
if(top==NULL){
printf("\nSorry stack is empty:Stack
underflow");
return;
}
p=top;
top=top->next;
return p;
} 205
Algorithm for Peek from an Linked-list based stack ADT
(Return whole node)
struct node* PeekNode(){
if(top==NULL){
cout<<"\nSorry stack is empty:Stack
underflow";
return;
}
p=top;
return p;
}
206
Algorithm for isEmpty in a Linked-list based stack ADT
int isEmpty(){
return (top == NULL); // Returns 1 if stack is empty, else
returns 0
207
Algorithm for ModifyTOP in an Linked-list based stack
ADT
209
Queue ADT
210
Queue ADT
● It's a derived concept of List, with restriction that insertion can
be done only at the end and the deletion only at the beginning
Operations on Queue
1) ENQUEUE- Equivalent to insert operation
2) DEQUEUE- Equivalent to delete operation (First inserted
element)
● Queues are also called as First in First Out (FIFO)
● Performing ENQUEUE operation when memory is full -
is an error.
● DEQUEUE operation in an empty queue- is an error.
Implementation of Queue ADT
1) Enqueue
Write a C++ program to implement the given problem
2) Display statement with separate functions for each algorithm.
3) Dequeue
4) ModifyFront / ModifyRear
5) PeekFront / PeekRear
6) isEmpty
7) isFull
8) Clear 213
Algorithm for insertion (Enqueue) in array based
queue ADT
void ENQUEUE(int d){
if(rear==max-1){
cout<<"\nSorry queue overflow; can't insert";
return;
}
if(front==-1)
++front;
++rear;
s[rear].data=d;
}
214
Algorithm for displaying the contents of array based
Queue ADT
void display(){
if(front==-1){
cout<<"\nSorry queue Underflow;
can't print";
return;
}
cout<<"\nThe queue contents are:\n";
for(int i=front;i<=rear;i++)
cout<<s[i].data<<"\t";
} 215
Implementation of Queue ADT
1) Enqueue
Write a C++ program to implement the given problem
2) Display statement with separate functions for each algorithm.
3) Dequeue
4) ModifyFront / ModifyRear
5) PeekFront / PeekRear
6) isEmpty
7) Clear
8) etc., 217
Algorithm for insertion (Enqueue) in linked-list based
queue ADT
void ENQUEUE(int d){
temp=new struct node;
temp->data=d;
temp->next=NULL;
if(front==NULL){
front=rear=temp;
return;
}
rear->next=temp;
rear=temp;
} 218
Algorithm for displaying the contents of linked-list
based Queue ADT
void display(){
if(front==NULL){
cout<<"\nSorry Queue is empty; can't print";
return;
}
p=front;
cout<<"\nThe queue contents are:\n";
while(p!=NULL){
cout<<p->data<<"\t";
p=p->next;
}
} 219
Algorithm for deletion (Dequeue) in Linked-List based
queue ADT - Return Data
int DEQUEUE(){
if(front==NULL){
cout<<"\nSorry Queue is empty; can't print";
return -1;
}
int x=front->data;
front=front->next;
return x;
} 220
Algorithm for deletion (Dequeue) in Linked-List based
queue ADT - Return Node
struct node* DEQUEUENode(){
if(front==NULL){
cout<<"\nSorry Queue is empty; can't print";
return NULL;
}
p=front;
front=front->next;
return p;
} 221
Worst Case Run-time complexity of Queue ADT
Algorithms
222
Homework - 12/09/2024
https://classroom.google.com/c/NjkxNzYwNzI0MjYy/m/Njg1MzkyMzky
MDMz/details
224
Applications of Stack ADT
225
Applications of Stack
1. String Reversal
2. String Concatenate
3. Backtracking
4. Balancing Parenthesis
5. Infix to Postfix Expression Conversion
6. Postfix Expression Evaluation
7. etc.,
226
Ex 1: Move the contents from One stack to
another stack
Write an algorithm to move the data / nodes from one stack to
another stack using linked list based implementation of stack ADT.
Option 2:
Option 1:
Void PUSH1(int d); //Algorithm to push in In a single PUSH and POP
stack1
functions, pass the stack refere
Void PUSH2(int d); //Algorithm to push in
as an additional argument
stack2
(top1/top2) 227
Int POP1(); // Algorithm for POP from
Ex 2: Reverse a String using Stack
● Create a char[] to store a string.
● Create a Stack.
● Push all characters, one by one.
● Then Pop all characters, one by one and put into the
char[].
● Finally, convert to the String.
228
Ex 3: Move and merge the contents of two
stacks to the third stack
Write an algorithm to merge the data / nodes from two different stacks, one
after another stack using linked list based implementation of stack ADT into
the third stack.
229
Ex 4: Concatenate two strings using stack
230
Ex.5 Algorithm for Balancing Parenthesis
(using stack)
int balance(char *exp){
n=strlen(exp);
for (i=0;i<=n;i++){
if (exp[i] equal to any of the open bracket)
PUSH(exp[i]);
else if (exp[i] equal to any of the close bracket){
if (stack is empty (or) exp[i] is not equal
to its pair)
return 0; //or print not balanced
else
POP();
}
if(stack is not empty)
return 0; //or print not balanced
else
return 1; //or print balanced 231
Ex. 6 Infix to Postfix Conversion (using stack)
Infix Expression
Ex: A + B
Postfix Expression
Ex: AB +
Prefix Expression
Ex: + AB 232
Ex. 6 Infix to Postfix Conversion (using stack)
Let A = 6 , B = 5 , C = 3
Postfix Evaluated
Expression Expression
1)ABC++ 1)14
2)ABC+* 2)48
3)AB/C* 3)3.6
4)58+4-3* 4)27
5)6523*8++3-* 234
Homework - 14/09/2024
Check weather the following expressions are
i) Balanced
ii) If balanced convert them to postfix
iii) Evaluate the postfix expression.
1) 4+{[(7*3)+5]+(2-8)}
2) a-{b*[c/(d+e)]-f}/g; Let a =5, b=3, c=10, d= 2,
e=1, f=4, g=2
3) 9+{4-[2*4]-7*(2-8)}
● Illustrate the implementation using Stack ADT using
appropriate visual illustrations. 235
Applications of Queues
● Breadth-First Search (BFS) in Graph Traversal
● Tree and Graph Algorithms
● Producer-Consumer Problem
● Scheduling and Task Management
● Real-Time Systems
● Messaging Systems
● Load Balancing
● Simulation of Customer Service Systems
236
Types of Queues
● Simple Queue
● Circular Queue
● Priority Queue (Min-Heap / Max-Heap Priority)
● Double Ended Queue (Not follows FIFO,
insertion/deletion can be done both in begin
and end)
● Double Priority Queue
237
“
End of Unit - II
238
UNIT - III
239
UNIT III
TREE DATA STRUCTURES
● Tree ADT
● Representation
● Traversals
● Binary Tree
● Expression trees
● Binary Search Tree
● AVL Trees
Tree ADT
● Tree ADT are a category of non-linear
data structures, in which each node may
have more than two neighbours.
● Every tree will have N nodes and N-1
edges.
● Top most node in a tree is called as a
root node.
● Other nodes are children of the root node.
Terminologies in Tree ADT
1. Root 10. Siblings
2. Leaf 11. Parent
3. Edges 12. Child
4. Path 13. Grandparent
5. Subtree 14. Ancestors
6. Depth 15. Descenders
7. Height 16. Internal Nodes
8. Forest 17. External Nodes
9. Degree of a node
Terminologies in Tree ADT
1. Root - Top node in a tree
2. Leaf - Last nodes in a tree without any children
3. Edges - Connections between two nodes
4. Subtree - Distinct trees that can be formed from a tree
5. Depth - Number of edges between node ‘N’ and root node
(Depth of root node = 0)
6. Height - Number of edges between root node and node
‘N’(Height of leaf node=0)
Height of root node = Height of tree
7. Path - Sequence of nodes between two nodes
8. Forest - More number of trees
Terminologies in Tree ADT Cont…
9. Degree of a node - Number of children for a node
10. Siblings - Nodes with same parent
11. Parent - Immediate ancestor of a node
12. Child - Immediate descendent of a node
13. Grandparent - Ancestor of a node
14. Ancestors - For a leaf node, the intermediate nodes till root node
are ancestors
15. Descenders - For a root node, the intermediate nodes till leaf
node are descenders
16. Internal nodes - Nodes excluding the leaf nodes and root node
17. External nodes - All the leaf nodes and root nodes are external
nodes
Types of Tree Data Structures
1. A General Tree - each node can have any
number of children
2. Binary Tree - each node can have maximum of 2
children
a. Binary Search Tree
b. AVL Tree
3. B-Tree
4. Splay Tree
5. Red-Black Tree
Types of Binary Trees
In a binary tree each node can have maximum of 2
children ( 0 or 1 child or 2 children)
1)Perfect Binary Tree - all the levels are filled
with nodes
2)Complete Binary Tree - not mandatory to fill
all the levels with nodes
3)Strict Binary Tree - nodes will have either 0 or
2 children
4)Skew Binary Tree - nodes will have either 0 or
Types of Binary Trees
247
Traversal in Binary Trees
● Process of visiting each nodes in a data structure at least once
(Ex:display)
● In trees traversal could be implemented in any of the following
mechanisms
1) Preorder - Process of visiting the node itself and then
recursively visiting children left to right. (Middle - Left -
Right)
2) Postorder - Process of recursively visiting children left to
right before visiting the node itself (Left - Right - Middle)
3) Inorder - Process of recursively visiting the left children,
then the node itself and then recursively visiting the right
children (Left - Middle- Right )
4) Level order - Process of visiting the nodes level by level
(No recursion) 248
Homework - 21/09/2024
Insert the following sequence in a level
order and construct a binary tree and
subsequently find the preorder, postorder
and inorder sequences.
1) M, O, Q, S, T, V, A, D, E, F
2) 4, 7, 1, 8, 9, 12, 5, 13, 2
3) cot, tat, mat, sun, raj, phone, table, van
249
Binary Search Tree (BST)
250
Binary Search Trees (BST)
▷ BST are extended versions of binary trees, in which
elements lesser than the root nodes moves to the left
sub-tree and the elements greater than the root node
moves to the right sub-tree.
▷ The first inserted element will be the root node.
▷ Linear cost of searching in linked list based linear data
structure are costly to implement.
▷ So, the non-linear BST data structure could make the
search problem easier as the data are arranged in
sequential order (smaller values to the left of root and
larger values to the right of the root)
▷ BST may not always look balanced after insertion
(depending on the input sequence) 251
Homework - 24/09/2024
1) Insert
2) Traversal Write a C++ program to implement the given problem
a) Preorder statement with separate functions for each algorithm.
b) Postorder
c) Inorder
d) Decendingorder
3) Delete
4) Search
5) Find Minimum
6) Find Maximum
7) Clear
253
8) etc.,
Implementation of a Binary Search Tree ADT
//Node initialization
struct node{
int data;
struct node *left;
struct node *right;
} *root=NULL, *temp=NULL;
Algorithm for Node Creation in BST
258
Algorithm for inorder Traversal
void inorder(struct node *T){
if(T!=NULL){
inorder(T->left); //L
cout<<T->data; //M
inorder(T->right); //R
}
}
259
Algorithm for Decending order Traversal
269
Expression Trees
● Evaluation of expressions are carried out by the
compiler using binary trees
● In a binary tree, the internal nodes will have the
operators and the external (leaf) nodes will have
the operands
● Binary trees are used for interpreting the
expressions
○ Directly on infix expression
○ Converting infix to postfix expression.
270
Expression Trees (Examples)
271
AVL Tree
272
AVL Trees
BF=Htl - Htr
|BF|=|Htl - Htr| <=1
● The value of BF for every node should be either {-
1, 0,or 1} to maintain the balance
-
condition.
-
Rotation of nodes in AVL Trees
Single Rotation
L
with Right (SRR)
Right Right Case
Single Rotation
R
with Left (SRL)
Left Right Case
Double Rotation SRL+SRR
L
SRL SRR
Right Left Case
Double Rotation SRR+SRL
L SRL
SRR
AVL Tree implementation
Problem Statement / Aim /
Objective
To implement the AVL Tree for a set of numbers (marks of students / set of
integers / scores by a individual players in certain number of innings). Write
appropriate (following set of) algorithms for handling the available data (set of
numbers ) and to structure them (Data structure)
1) Insert
2) Traversal (same as BST)
a) Preorder
Write a C++ program to implement the given problem
b) Postorder statement with separate functions for each algorithm.
c) Inorder
d) Decendingorder
3) Delete
4) Search (same as BST)
5) Find Minimum (same as BST)
6) Find Maximum (same as BST)
7) Clear (same as BST)
8) etc., 280
Homework - 08/10/2024
Construct AVL tree for the following
sequence of inputs
1)G, L , O, P, E, F, X, Z, A, M
2)98, 45, 23, 76, 34, 67,12, 7, 3
3)5, 7, 8, 12, 34, 2, 4, 6, 8
4)Car, Bus, Van, Tempo, Lorry, Ship,
Plane 281
Implementation of a AVL Tree ADT
//Node initialization
struct node{
int data;
struct node *left;
struct node *right;
int height;
} *root=NULL, *temp=NULL;
Algorithm for Node Creation in AVL Tree
T2 T2
y = x -> y->left=x;
right;
x->right=T2;
T2 = y-
285
>left;
Algorithm for SRL
struct node *SRL(struct node *x){
struct node * y = x -> right;
struct node *T2 = y->left;
y->left=x;
x->right=T2;
x->height = 1+max(height(x-
>right),height(x->left));
y->height = 1+max(height(y-
>right),height(y->left));
return y; 286
Single Rotation with Right (SRR)
BF=2
y
x
Single Rotation
x
with Right (SRR) y
T2
T2
x = y ->left; x->right=y;
T2 = x->right; y->left=T2;
287
Algorithm for SRR
struct node *SRR(struct node *y){
struct node * x = y ->left;
struct node *T2 = x->right;
x->right=y;
y->left=T2;
x->height = 1+max(height(x-
>right),height(x->left));
y->height = 1+max(height(y-
>right),height(y->left));
return x; 288
Insertion in an AVL Tree
L
if(balance > 1 && d < T->left->data)L
struct node *insert(struct node *T, int d){
R return SRR(T); //perform SRR
int balance;
if(T==NULL) R else if (balance < -1 && d >T->right->
return SRL(T); //perform SRL
T=createnode(d);
else if(balance > 1 && d > T->left->d
elseif(d>T->data) BST T->left = SRL(T->left); //perform
L SRL
T->right=insert(T->right,d); insertion
return SRR(T); //perform SRR
elseif(d<T->data) routine R
}
T->left=insert(T->left,d);
//Find & update height of the node else if(balance < -1 && d < T->right->
T->height=1+max (height(T->left),height(T- {
>right)); T->right = SRR(T->right);//perform S
R
//Find balance factor of the node return SRL(T); //perform SRL
} L
balance = height(T->left)-height(T->right); return T;
}
Homework - 10/10/2024
Write AVL tree Algorithms for the
following
1)Algorithm to print the height of
every nodes.
2)Algorithm for finding and printing
the balance factor of every nodes.
290
Algorithm for Deletion in AVL Tree
struct node *Delete(struct node *T, int else if(balance > 1 && d > T->left-
d){ >data){ L
int balance; T->left = SRL(T->left); //perform
R SRL
//Here write the BST deletion return SRR(T); //perform SRR
routine for }
//3 cases (0child, 1 child & 2 else if(balance < -1 && d < T->right-
children) >data){ R
//Find height of the node L
T->height=1+max (height(T- T->right = SRR(T->right);//perform
L
L
>left),height(T->right)); SRR
//Find balance factor of the node return SRL(T);//perform SRL
R
balance = height(T->left)-height(T- }
R
>right);
if(balance > 1 && d < T->left->data) 291
Run time and Space Complexity of AVL Algorithms
292
“
End of Unit - III
293
UNIT - IV
294
UNIT IV
DISJOINT SET AND GRAPH
● Disjoint Set ADT
○ Dynamic equivalence problem
○ Smart union algorithms
○ Path compression
● Graph ADT
○ Terminology and Representations
○ Graph traversal
■ Breadth First Search (BFS)
■ Depth First Search (DFS)
○ Topological Sort
○ Shortest Path Algorithm
■ Dijkstra’s Algorithm
○ Minimum Spanning Tree
■ Prim's Algorithm
■ Kruskal's Algorithm
Dynamic Equivalence Problem
● Let elements ‘a’ and ‘b’ be the two elements of set S
● A relation between two elements are represented by ⟒
● We say that a ⟒ b (a is related to b), if they belong to the same set.
● Equivalence relation between two elements have to satisfy the
following 3 properties.
○ Reflexive: a ⟒ a, for all a ∈ S
○ Symmetric: a ⟒ b, if and only b ⟒ a
○ Transitive:a ⟒ b, and b ⟒ c => a ⟒ c
● Dynamic Equivalence problem expresses the problem of deciding,
given two elements, whether they are related to each other.
● This could be solved using the disjoint sets.
Disjoint Set ADT
● An element will be present only in one
set.
● No duplication allowed
● Disjoint sets are collection of
dissimilar elements in a single group
● Each data /item will be in exactly one
set
● Collections of disjoint sets are called
as a partition
Why we need Disjoint Set Data Structure?
● To keep track of connected data (related
data), the use of disjoint sets makes this
process easier.
● It is easier to check the association
between two elements, weather they
belong to the same set / subset.
● Used to easily merge two sets of data
(related data)
Operations / Algorithms in Disjoint Sets
309
Implementation of Disjoint Sets (Smart - Union
Algorithms)
//Node Initialization
parent
struct node{
int data; dat
a
int rank; rank
node
struct node *parent;
}
310
MakeSet Algorithm
void MakeSet(struct node *x,
int d){
x -> data = d ; x->parent =x
x -> rank = 0;
d x->data =d
x -> parent = x; x->rank =0
} node *x
311
Homework - 19/10/2024
Implement Tree based disjoint set on the sequence of
following items.
Mango, Pen, Potato, Apple, Spinach, Bottle, Banana, Chair,
Orange, Watermelon, Carrot, Broccoli, Cabbage, Book
Implement the union operations on the data separating
them as 3 sets of “Fruits”, “Vegetables and “Nonedible”
i) Union by Rank
ii) Path Compression 312
Find Algorithm
struct node* Find(struct node *x){
if(x!=x->parent)
x->parent = Find(x-
>parent);
return x->parent;
} 313
Union Algorithm
void Union(struct node *x,struct node *y){
Link(Find(x),Find(y));
}
Link Algorithm
void Link(struct node *x,struct node *y){
if(x->rank>y->rank)
y->parent = x;
else{
x->parent = y;
if(x->rank==y->rank)
y->rank++;
}
314
}
Run time and Space Complexity of Disjoint Set
Algorithms
315
Applications of Disjoint Sets
● Graph Algorithms - Kruskal's Minimum Spanning Tree
algorithm and cycle detection in graphs.
● Image Processing - Image segmentation algorithms
to group pixels with similar characteristics together.
● Network Connectivity - Determine if two nodes are in
the same network or to find the minimum spanning
tree of a network.
● Game Theory - To represent the relationships between
players and their strategies.
● Computer Graphics - Determine whether two objects
in a scene intersect or overlap.
● Robotics - Relationships between objects or obstacles
in the robot's environment, for navigation and path
316
planning.
UNIT IV
DISJOINT SET AND GRAPH
● Disjoint Set ADT
○ Dynamic equivalence problem
○ Smart union algorithms
○ Path compression
● Graph ADT
○ Terminology and Representations
○ Graph traversal
■ Breadth First Search (BFS)
■ Depth First Search (DFS)
○ Topological Sort
○ Shortest Path Algorithm
■ Dijkstra’s Algorithm
○ Minimum Spanning Tree
■ Prim's Algorithm
■ Kruskal's Algorithm
Graph ADT
318
Graph Data Structure
Most of the real world problems could be solved using
Graph ADTs
Examples:
● Map of City
● Computer Networks
● Travelling Salesman Problem
● Shortest Path Problems
● Neurons in human brain
● Social Media (FB, instagram, Linkdein, etc.,)
etc.,
Graph: Definition & Terminology
323
Graph Representation
324
Representation of Graphs
326
Graph Traversals
327
Traversal in Graphs
Depth First Search (DFS)
● Implementation using Recursive
algorithms or Stack ADT
Step 2 - Select any vertex as starting point for traversal. Visit that vertex and insert it into the Queue.
Step 3 - Visit all the non-visited adjacent vertices of the vertex which is at front of the Queue and
insert them into the Queue.
Step 4 - When there is no new vertex to be visited from the vertex which is at front of the Queue then
delete that vertex.
Step 6 - When queue becomes empty, then produce final spanning tree by removing unused edges
from the graph
330
Graph Traversal Implementation
Steps involved
1.Node Initialization
2.Initialize Graph (Adj. matrix /
Adj. List)
3.Add Edges / Connect Edges
4.Perform Traversal (DFS / BFS)
Node Initialization in Graph
struct Node {
int vertex;
struct Node* next;
}* G[MAX], *p, *temp; // Adjacency list representation
of the graph
bool visited[MAX]; // Visited array for DFS
int vertices;
332
Initialize Graph
Graph(int v) { //Pass number of vertices
p = NULL;
temp = NULL;
vertices = v;
for (int i = 0; i < v; i++) {
G[i] = NULL;
visited[i] = false;
}
} 333
Add edges to the graph
void AddEdges(int edges[][2], int e) {
for (int i = 0; i < e; i++) {
int vs = edges[i][0];
int vd = edges[i][1];
insert(vs, vd); // Add edge from vs to vd in the
adjacency list
}
}
334
Insert vertices in Adj. List representation
void insert(int vs, int vd) {
temp = createNode(vd);
if (G[vs] == NULL) {
G[vs] = temp; // First node in the list
return;
}
p = G[vs];
while (p->next != NULL) // Traverse to the end of the list
p = p->next;
p->next = temp;
}
335
Create a Node to added to the Graph
void createNode(int v) {
temp = new Node;
temp->vertex = v;
temp->next = NULL;
return temp;
}
336
DFS Traversal (using Recursion)
void DFS(int source) {
cout << source << " --> "; //Print the source vertex @ each iteration;
visited[source] = true; //Mark the source node as visited @ each
iteration;
Node* p = G[source]; //Pointer for the first node in the adjacency list
while (p != NULL) { //Repeat till all the edges connected to present vertex is
visited
int vertex = p->vertex;
if (!visited[vertex])
DFS(vertex); //Repeat algorithm till visiting all
vertices
p = p->next;
}
} 337
BFS Traversal (using Queues)
void Graph::BFS(int source) {
Queue q;
q.Enqueue(source);
visited[source] = true;
while (!q.isEmpty()) {
int current = q.Dequeue();
cout << current << " --> ";
Node* p = G[current];
while (p != NULL) {
int vertex = p->vertex;
if (!visited[vertex]) {
q.Enqueue(vertex);
visited[vertex] = true;
}
p = p->next;
}
}
338
}
Topological Sort
339
340
Shortest Path Algorithm
(Dijkstra's)
341
342
Minimum Spanning Tree
343
344
345
“
End of Unit - IV
346
UNIT - V
347
UNIT V
HASHING, SORTING ALGORITHMS & CASE STUDY
Hashing
○ Hash Table
○ Hash Function
○ Load Factor
○ Collision
○ Separate chaining
○ Open addressing
○ Rehashing
Sorting Algorithms
○ Bubble Sort - Karthika
○ Insertion Sort - Naveen
○ Merge Sort - Sri mahalakshmi
○ Quick Sort - Sabarnitha
○ Heap Sort - Kalaivani
Case Study
○ Contact Management System - Niranjan / Hariprasad 348
Hashing
349
Introduction to Hashing
It maps the location / index of the hash table to store the data.
Key/Data Address
input Hash Function h(N) /index
Output of
Hash Table
Hash Table
● A hash table for a given key / data consists of hash
function h(N) and array / vector (called table) of size ‘N’.
● Array into which data inserted using hash function is
called hash table.
● It is very fast to insert and search in hash table.
● Easy to program than other non-linear data structures.
Hashing
● Hashing is the process of inserting elements into
the hash table.
● The goal is to store the item (along with key ‘k’) at
index i=h(k) in the hash table.
354
Collision Avoidance
356
Open Addressing
357
Open Addressing
Search hash table (array) in a systematic fashion to find
empty cells and insert the new item if collision occurs.
Linear probing:
● Handles collision by placing the colliding item in the next
(circularly) available space in the hash table.
● Search sequentially for vacant cells until empty cell is
found.
● x+1, x+2,, x+3 ….
● Clustering problem occur - as array get fulls, the cluster
grows further
Open Addressing - Linear Probing Method
Insert elements 89, 18, 49, 58, 69 in a hash table of size 10 using
quadratic probing
Open Addressing - Double Hashing Method
● Better solution for avoiding clustering
● The better choice for double hashing f(i)=i
hash2(x)
● It will not provide const step size.
● Stepsize = const - (key % const)
● Where const = a small prime number less than
the table size.
● During double hashing, we must consider that
Open Addressing - Double Hashing Method
Insert elements 89, 18, 49, 58, 69 in a hash table of size 10 using
double hashing
366
Separate Chaining
368
Implementation of Linear Probing (Open Addressing)
#define tablesize 13
// Initialize Hash Table
// Node Initialization
void initialize() {
struct node {
for (int i = 0; i < tablesize; i+
int data;
+)
}table[tablesize];
table[i].data = -1; // empty
// Hash Function slot
Implementation
}
int hash(int key) {
return key % tablesize;
369
Insertion Algorithm in Hash Table (Linear Probing)
// Insertion Algorithm
void insert(int key) {
int index = hash(key);
int i = 0;
while (table[(index + i) %
tablesize].data != -1)
i++; //on collision looks for next
vacant cell 370
Display Algorithm in Hash Table (Linear Probing)
// Deletion Algorithm
void Delete(int key) {
int index = find(key);
if (index == -1) {
cout<<"\nElement not found in the
hash table.";
return;
}
table[index].data = -1;
} 372
Search Algorithm in Hash Table (Linear Probing)
// Find the location of key element
int find(int key) {
int index = hash(key);
int i = 0;
while (table[(index + i) % tablesize].data != -1)
{
if (table[(index + i) % tablesize].data ==
key)
return (index + i) % tablesize;
i++;
} 373
Homework - 29/10/2024
1) Insert the following elements in a hash table of size 11.
Where the hash function is h(n) = n % table_size. 45, 11, 33,
41, 55, 67, 77, 12 Avoid collision using
i) Linear probing ii) Quadratic probing iii) Double hashing
iv) Separate Chaining
2) Insert the following in a hash table of size 12. Let the hash
function h(n) be data % table size.
14,16,4,8,17,19,12,93,94,32. Avoid collision using
i) Linear probing ii) Quadratic probing iii) Double hashing
iv) Separate Chaining
374
Implementation of Separate
Chaining
375
Implementation of Separate Chaining
#define tablesize 13
//Node Initialization
struct node{
int data;
struct node *next;
}**table,*pos,*temp,*p;
Hash Function Implementation
377
Initialize Hash Table
void intialize(){
table=(struct node**)malloc(tablesize*sizeof(struct
node *));
for(i=0;i<tablesize;i++)
table[i]=NULL;
}
Insert Elements to Hash Table
void insert(int key){
pos=find(key); //find algo to be called for locating
position
if(pos==NULL){
temp=(struct node*)malloc(sizeof(struct node));
p=table[hash(key)];
temp->next=p;
temp->data=key;
table[hash(key)]=temp;
}
Find algo to locate position for insertion
void display(){
if(table==NULL){
cout<<”\nSorry hash table is empty";
return;
}
printf("\nIndex\t Values in table");
for(i=0;i<tablesize;i++){
p=table[i];
cout<<”\n”<<i<<”\t";
while(p!=NULL){
cout<<p->data<<”-->”;
p=p->next;
}
}
Deletion of element from hash table
//if the data to be deleted is not @ the
void Delete(int key){ first position,
if(table==NULL){ //then traverse to locate the element to
printf(“Hash table be deleted
empty”);
temp=find(key);
return;
} p=table[hash(key)];
p=table[hash(key)]; while(p->next!=temp)
//if data is at first position in the hash
table p=p->next;
if(p!=NULL && p->data==key) p->next=temp->next;
{ free(temp);
table[hash(key)]=p- }
>next;
free(p);
Run-time Analysis of Hashing Algorithms
385
Sorting
387
What is Bubble Sort?
Bubble Sort is a simple sorting algorithm that repeatedly
steps through the list to be sorted, compares each pair
of adjacent items, and swaps them if they are in the
wrong order.
This process is repeated until no swaps are needed,
indicating that the list is sorted.
-It's one of the simplest sorting algorithms to understand and
implement
Best case:o(n^2)
1st optimized version
Best case:o(n^2)
2nd optimized version
void bubbleSort(int arr[], int n) {
}
Animation
Best case:O(n)
Insertion Sorting
398
Insertion Sorting
Insertion sort is a fundamental sorting algorithm
that builds the final sorted array by inserting
elements into their correct position one at a time.
399
Operations of Insertion Sort
400
401
Insertion Sort Algorithm
void insertionSort(int a[], int n) {
int i, temp, j;
for (i = 1; i < n; i++) {
temp = a[i]; //Store the current element in a temporary
variable
j = i - 1;
while (j >= 0 && a[j] > temp) {
a[j + 1] = a[j]; //Move the current element one position
ahead
j = j - 1;
}
a[j + 1] = temp;
}
}
402
Pros and Cons of Insertion Sort
Advantages:-
● Simple Implementation
● Efficient for small datasets
Disadvantages:-
● Inefficient for large data sets
● Quadratic Time complexity
403
Worst Case Run-Time complexity of Insertion Sort
Best case:O(n)
Heap Sorting
405
Introduction to Heap Sorting
● A heap is binary tree-based data structure that satisfies the heap property :
the value of each node is greater than or less than to the value of its children
depending on the type.
● Types:
Min Heap
The root node contains the minimum value, and the values
increase as you move down the tree.
Max Heap
The root node contains the maximum value, and the values
decrease as you move down the tree.
406
407
Operations in Heap
● Insert : Adds a new element to the heap while
maintaining the heap property.
408
Heapify Algorithm
412
Quick Sorting
413
Quick Sort
● Quick Sort is a fast sorting algorithm
that works by splitting a large array
of data into smaller sub-arrays.
● This implies that each iteration splits
the input into two components, sorts
them and then recombines them.
● The technique is highly efficient for
big data set. 414
Steps in Quicksort
415
Choice of Pivot Element
There are many different choices for
picking pivots.
● Pick first element as pivot.
● Always pick the last element as a
pivot.(mostly used)
● Pick a random element.
● Pick the middle as the pivot.
● Pick the median as the pivot.
416
Example
417
Example
418
Example
419
Example
420
Example
421
Example
422
Example
423
Algorithm to Partition the Array
int partition(int arr[], int low, int high) {
int pivot = arr[high]; // Select the pivot element
int i = (low - 1); // Index of smaller element
for (int j = low; j <= high - 1; j++) {
// If current element is smaller than or equal to
pivot
if (arr[j] <= pivot) {
i++; // Increment index of smaller element
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
} 424
Quick Sort Algorithm
void quickSort(int arr[], int low, int high) {
if (low < high) {
// pi is partitioning index, arr[pi] is now at right place
int pi = partition(arr, low, high);
*a = *b; cout<<arr[i];
*b = t; cout<<"\n";
} }
426
Run-time Analysis of Quick Sort
Best Case: Ω (N log (N))
● The best-case scenario for quicksort occur when the pivot chosen at the each step
divides the array into roughly equal halves.
● In this case, the algorithm will make balanced partitions, leading to efficient Sorting.
● The worst-case Scenario for Quicksort occur when the pivot at each step consistently
results in highly unbalanced partitions.
● When the array is already sorted and the pivot is always chosen as the smallest or
largest element.
● To mitigate the worst-case Scenario, various techniques are used such as choosing a
good pivot (e.g., median of three) and using Randomized algorithm
427
Pros and Cons of Quick Sort
Advantages:-
● It is a divide-and-conquer algorithm that makes it easier to solve problems.
● It is efficient on large data sets.
● It has a low overhead, as it only requires a small amount of memory to function.
Disadvantages:-
● It has a worst-case time complexity of O(N2), which occurs when the pivot is
chosen poorly.
● It is not a good choice for small data sets.
● It is not a stable sort, meaning that if two elements have the same key, their
relative order will not be preserved in the sorted output in case of quick sort,
because here we are swapping elements according to the pivot’s position
(without considering their original positions).
428
Run-time Analysis of Sorting
Algorithms
431
Run-time Analysis of Sorting
Algorithms
433
“
Thank You!
434
434