0% found this document useful (0 votes)
15 views434 pages

Data Structures with Algorithmic Analysis (study material)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views434 pages

Data Structures with Algorithmic Analysis (study material)

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 434

23EC381 - Data Structures with Algorithmic

Analysis
III Sem B.E ECE ‘A’ (2023 - 2027 Batch)
Academic Year 2024 - 2025 (Odd Semester)

Dr. J.Senthil Kumar,


Associate Professor (Sr.)/ECE
Mepco Schlenk Engineering College, Sivakasi
[email protected]
Steps to follow for writing the Algorithms in Test

1) Description on the problem statement and data


structures.
2) Pictorial representation of data structure before
execution of the algorithm
3) Write the algorithm (include comments where
necessary)
4) Pictorial representation of data structure after
execution of the algorithm
5) Worst / Best/ Average case run time / space
2
complexity analysis with Big Oh
Assignment - 1 (Deadline:20/09/2024)

1) Implement singly circular linked list for


implementation of the chosen problem statement for
your batch with nodes with multiple data and data types
that includes the following algorithms
● Insert Also use file handling concept in C++, to
write the contents of the list to a .txt file.
● Display Write an algorithm to complete this task as
● Modify well.
● Search Write the Worst case run-time of each
algorithms
● Delete (based on value)
● Clear (make the list empty)
● Insert at beginning
● Insert at particular position
● Delete at Beginning
● Delete at End
● Delete at particular position
Assignment - 1 (Deadline: 20/09/2024)

2) Implement doubly circular linked list for implementation


of the chosen problem statement for your batch with nodes
with multiple data and data types that includes the following
algorithms Also use file handling concept in C++, to
● Insert write the contents of the list to a .txt file.
● Display Forward Write an algorithm to complete this task as
● Display Backward Write the Worst well.
case run-time of each
● Modify algorithms
● Search Forward
● Search Backward
● Delete (based on value)
● Clear (make the list empty)
● Insert at beginning
● Insert at particular position
● Delete at Beginning
● Delete at End
# RollNo. Date Mark
Assignment 1 Submission
21. 31,60 - 0
# RollNo. Date Mark # RollNo. Date Mark
22. 32,39 - 0
1. 47,55 19/9 100 11. 5,6 28/9 70
23. 33,58 - 0
2. 41,62 19/9 100 12. 7,8 - 0
24. 34,45 - 0
3. 34,45 20/9 100 13. 11,12 28/9 70
25. 35,46 28/9 80
4. 56,57 20/9 100 14. 15,17 16/10 70
26. 36,38 03/10 80
5. 13,14 21/9 80 15. 18,19 27/9 90
27. 37,63 28/9 85
6. 44,61 21/9 90 16. 20,21 17/10 70
28. 40,54 28/9 80
7. 53,59 23/9 95 17. 22,23 18/10 70
29. 42,43 - 0
8. 9,10 26/9 80 18. 24,25 28/9 70
30. 48,49 - 0
9. 1,2 - 0 19. 26,27 18/10 70
31. 50,52 - 70
10. 3,4 - 0 20. 28,29 27/9 85
32. 30,L01 1/10 80 5
Assignment - 2 (Deadline: 08.11.2024)
https://www.hackerrank.com/domains/data-structures

Solve all the Data


Structure Algorithms
listed under Basic and
Intermediate
categories in
Hackerrank website
using either C / C++
Programming
Every
Language only.individual
student should send
the updated status
(with their profile
name) and submit a
printed copy as well.
6
Course Objectives
● To study the design and applications of linear
ADTs such as List, Stack and Queue.
● To implement tree and graph based Non
Linear ADTs.
● To implement various sorting algorithms.

7
Course Outcomes
At the end of the course, the students will be able to

CO1. Analyze the running time of various algorithms.

CO2. Develop the various linear data structures such as List,


Stack and Queue ADTs.

CO3. Develop the various nonlinear data structures such as


Trees, Graphs.

CO4. Apply Hashing and Set concepts for real world


applications.

CO5. Implement sorting algorithms for different applications. 8


Concept Map of the Course

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

Queue ADT: array-based & linked list based


implementation - Types of Queue- Applications
Stack ADT: array-based & linked list based
implementation - Applications of Stack: Balancing
Symbols, Infix to Postfix Conversion, Postfix
Expression Evaluation

11
UNIT III - TREE DATA STRUCTURES

Tree ADT - Representation - Traversals -


Binary Tree - Expression trees - Binary
Search Tree - AVL Trees

12
UNIT IV - DISJOINT SET AND GRAPH

Disjoint Set ADT - Dynamic equivalence problem -


Smart union algorithms - Path compression –
Applications Graph - Traversals - Topological Sort -
Prim's and Kruskal's Algorithms - Dijkstra’s
Algorithm

13
UNIT V - HASHING, SORTING ALGORITHMS AND CASE
STUDY

Hashing: Hash Table - Hash Function -


Load Factor - Collision- Collision
Resolution: Separate Chaining, Open
Addressing Sorting Algorithms: Bubble
Sort, Insertion Sort, Merge Sort, Quick
Sort, Heap Sort Case Study: Contact
Management System
14
Homework - 30/07/2024
1) Write a C Program to find the product of two numbers.

2) Write a C Program to find the product of two numbers using functions.

3) Write a C Program to find the product of two numbers using structures.

4) Write a C Program to find the product of two numbers using function


inside a structure.

5) Write a C Program to find the product of two numbers using pointer


variables, functions and structures

6) Write a C Program to find the product of two numbers using pointer


variables, functions and returning the structure to main function

15
1.C Program to find the product of two numbers
#include<stdio.h>

int main(){

int x,y,z;

printf("enter two numbers");

scanf("%d %d",&x,&y);

z=x*y;

printf("the product of two numbers %d",z);


Code Courtesy:
return 0; Sri Mahalakshmi V
II ECE A
} 16
//2.C Program to find the product of two numbers
using functions.
#include<stdio.h>
int product(int x,int y){
return x*y;
}
int main(){
int l,m;
printf("enter any two numbers");
scanf("%d %d",&l,&m);
printf("the product of the two numbers is %d",product(l,m));
Code Courtesy:
Sri Mahalakshmi V
return 0; II ECE A

} 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.

8) Write a C++ Program to find the product of two numbers using


functions.

9) Write a C++ Program to find the product of two numbers using


structures.

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

scanf() function in C language is replaced with cin object in C++


printf() function in C language is replaced with cout object in C++

24
//7.C++ Program to find the product of two numbers

#include<iostream> //Header file in C++


using namespace std; //Represents usage of standard
header
//(instead of user defined one)
int main(){
int x,y,z;
cout<<"My first C++ program"; //cout is an object; "<<" is
an insertion operator
cout<<"\nEnter two numbers";
cin>>x>>y; //cin is an object; ">>" is an extraction operator
z=x*y;
cout<<"The product of two numbers:"<<z;
25
//8.C++ Program to find the product of two numbers
using functions.
#include<iostream>
using namespace std;
int product(int x,int y){
return x*y;
}
int main(){
int l,m;
cout<<"C++ prog using function";
cout<<"\nEnter any two numbers";
cin>>l>>m;
cout<<"\nThe product of the two numbers
is:"<<product(l,m);
return 0;
}
26
//9.C++ Program to find the product of two
numbers using structures.
#include<iostream>
using namespace std;
typedef struct {
int n1;
int n2;
} product;
int main() {
product calc;
int result;
cout<<"C++ prog using structure";
cout<<"\nEnter the first number: ";
cin>>calc.n1;
cout<<"\nEnter the second number: ";
cin>>calc.n2;
result = calc.n1*calc.n2;
cout<<"\nThe product of "<<calc.n1<<" and "<<calc.n2<<" is "<<result;
return 0;
}
27
//10.C++ Program to find the product of two numbers
using functions inside structures.
#include<iostream>
using namespace std;
typedef struct {
int n1;
int n2;
int pro(int x,int y){ Functions could be
return x*y;
}
} product;
included inside a
int main() {
product calc;
structure in C++
int result;
language.
cout<<"C++ prog using function inside a structure";
cout<<"\nEnter the first number: ";
cin>>calc.n1;
cout<<"\nEnter the second number: ";
cin>>calc.n2;
result = calc.pro(calc.n1,calc.n2);
cout<<"\nThe product of "<<calc.n1<<" and "<<calc.n2<<" is "<<result;
return 0;
} 28
//11.My first OOP in C++
//OOP in C++ to find the product of two numbers (using OOP concepts)
//without data hiding (data encapsulation)
#include<iostream>
using namespace std;
class product{
public: //Public access specifier; gives global access across the code
int n1;
int n2;
int pro(int x,int y){
return x*y;
}
};
int main() {
product calc; //'product'->name of class; 'calc'->object
int result;
cout<<"My first OOP in C++";
cout<<"\nEnter the first number: ";
cin>>calc.n1;
cout<<"\nEnter the second number: ";
cin>>calc.n2;
result = calc.pro(calc.n1,calc.n2);
cout<<"\nThe product of "<<calc.n1<<" and "<<calc.n2<<" is "<<result;
return 0;
}
29
//12.My first OOP in C++
//OOP in C++ to find the product of two numbers (using OOP concepts)
//with data hiding (data encapsulation)
#include<iostream>
using namespace std;
class product{
private: //Private access specifier; gives access only inside class
int n1;
int n2;
public: //Public access specifier; gives global access across the code
void getdata(){
cout<<"\nEnter two numbers: ";
cin>>n1>>n2;
}
int pro(){
return n1*n2;
}
};
int main() {
product calc; //'product'->name of class; 'calc'->object
int result;
cout<<"My first OOP in C++ with data hiding";
calc.getdata();
result = calc.pro();
cout<<"\nThe product is: "<<result;
return 0;
}
30
Homework - 31/07/2024
1. Write an OOP in C++ to find the sum and
average of N numbers in an array.
2. Write an OOP in C++ to compute the area of
square, circle, rectangle and triangle.

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

Secondary /Non- Primitive/


Primary / Primitive/ Built- User defined Data Structure
in Data Structure

Static Dynamic
Basic constants /
Pointers
Data types

Arrays Structure Linear Non-linear


int
Dynamic
Trees
array
char
List Graphs
float
Hash
Stack
tables
double
Disjoint
Queue
Sets 52
Homework - 02/08/2024
1. Write an OOP in C++ to swap two numbers,
swap two strings, and swap two characters.
2. Write an OOP in C++ to compute the roots of a
quadratic equation.
3. Write an OOP in C++ to print the highest
possible demonization of the Rupees entered.
Ex : Input: Rs. 5893/- Rs.50/- -> 1
Output should be Rs.20/- -> 2
Rs.2000/- -> 2 Rs.10/- -> 0
Rs.500/- -> 3 Rs.5/- -> 0
Rs.200/- -> 1 Rs.2/- -> 1
Rs.100/- -> 1 Re.1/- -> 1 53
1. OOP in C++ to swap two numbers, swap two strings, and
swap two characters.(Homework - 02/08/2024)

#include <iostream> void strSw() {


#include <cstring> char temp[100];
using namespace std; strcpy(temp, n5);
strcpy(n5, n6);
class Swap { strcpy(n6, temp);
private: }
int n1, n2; void charSw() {
char n5[100], n6[100], tmp1[100]; char temp = n3;
char n3, n4, tmp; n3 = n4;
n4 = temp;
public: }
void getData() { void printResults() {
cout << "Enter two numbers: "; cout << "The swapped numbers are: " << n1 << " and "
cin >> n1 >> n2; << n2 << endl;
cout << "Enter two characters: "; cout << "The swapped characters are: " << n3 << " and "
cin >> n3 >> n4; << n4 << endl;
cout << "Enter two strings: "; cout << "The swapped strings are: " << n5 << " and " <<
cin >> n5 >> n6; n6 << endl;
} }
void swNo() { };
int temp = n1; int main() {
n1 = n2; Code Courtesy:
Swap c;
n2 = temp; c.getData(); Sri Mahalakshmi V
} c.swNo(); II ECE A
c.charSw();
c.strSw(); 54
2. OOP in C++ to compute the roots of a quadratic equation.
(Homework - 02/08/2024)
int main() {
#include <iostream>
Quad roots;
#include <cmath>
roots.getdata();
using namespace std;
roots.calc();
class Quad {
return 0;
private:
}
int a, b, c;
float r1, r2;
public:
void getdata() {
cout << "Enter coefficients a, b, and c: ";
cin >> a >> b >> c;
}
void calc() {
float dis = b * b - 4 * a * c;
r1 = (-b + sqrt(dis)) / (2 * a);
r2 = (-b - sqrt(dis)) / (2 * a);
cout << "Root 1 = " << r1 << endl; Code Courtesy:
cout << "Root 2 = " << r2 << endl; Sowmiya S
} II ECE A
}; 55
3. OOP in C++ to print the highest possible demonization of the
Rupees entered. (Homework - 02/08/2024)
void Denomination::deno() {
#include <iostream>
for (int i = 0; i < 10; i++) {
using namespace std;
if (n >= notes[i]) {
class Denomination {
notecount[i] = n / notes[i];
private:
n = n % notes[i];
int n;
}
int notes[10] = {2000, 500, 200, 100, 50, 20, 10, 5, 2, 1};
}
int notecount[10] = {0};
cout << "Denominations:" << endl;
public:
for (int i = 0; i < 10; i++) {
void getdata();
if (notecount[i] != 0) {
void deno();
cout << notes[i] << ": " << notecount[i] <<
};
}
}
void Denomination::getdata() {
}
cout << "Enter the amount: ";
int main() {
cin >> n;
Denomination d;
}
d.getdata(); Code Courtesy:
d.deno(); Vijay S K
return 0; II ECE A
}
56
Abstract Data Types (ADTs)

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.

ADT = Interface + Implementation (through


algorithms)
Interface - Properties of ADT and especially the operations
that it supports. 58
Interface vs Implementation (in class /
structure)

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)

● Code easy to understand


● Implementation of ADT can be changed, with the
program that already implements it.

ADT = Data + Operations


bundled along with it
(Ex: String - > Operations are finding length, concat,
compare, search etc.,)
60
ADT vs Data Structures
ADT - Tells only abstraction, not cares about
implementation. (Answers the question of what is
implemented?)

Data Structures - (Answers the question of how it is


implemented?)

● Specifies how you represent data, store


them and organize them.
● Gives you the ways for implementing
the ADT 61
62
Linear Data Structures
● A data structure is said to be linear, if the
available elements are arranged in a proper
sequence (one after another).
● Any element / data / node in a linear data
structure will have maximum of only two
neighbours. It can also have only one neighbour
as well.
Some of the common linear data structures are:
1) Array
2) List
3) Stack 63
Non-Linear Data Structures
● A data structure is said to be non-linear, if the
available elements are arranged /stored in a
proper sequence in the computer memory.
● Any element / data / node in a non-linear data
structure may have more than two
neighbours.
Some of the common linear data structures are:
1) Trees
2) Graphs
3) Disjoint Sets
4) Hash Tables 64
Operations supported on Linear Data
Structures
Algorithms written for the data structure will carry out the intended
operations on the data.

Few major operations supported on linear data structure are:

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

0 1. Ram Apple iphone 13 94655…


0
. 2. Arnold Oppo A74 96545…
. .
struct
. .
node{
. .
int Data;
. 60. Suriya Samsung S24 98645…
} s[60]; 59
struct mobile{
int Sno;
string Name;
string Brand;
string Model;
long int Number;
59 } s[60]; 72
Array vs List

Features Array List

Size Fixed Can grow / shrink dynamically

Type of Homogeneous Heterogeneous


Elements

Memory Continuous Random


Allotment

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

Speed of Faster (memory is Slower (memory is not continuous)


Accessing continuous)
elements

73
Array based List ADT vs Linked List
Features Array based List ADT Linked List (Pointer based)

Implementation Using arrays Using pointers

Memory allotment Continuous Random

Memory Access Random access Sequential access


mechanism (Ex:Digital mp3 music player) (Ex:Audio magnetic tapes )

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)

Running time and High Low


space requirement

Access Speed Faster Slower


74
Array-based Implementation of
List ADT

75
Array based implementation of List ADT

● All operations (Algorithms) on list are


implementations are implemented using
array concepts.
● Either static or dynamic array can be
implemented.
● But it is recommended to use dynamic
arrays to make the list ADT / data structures
to be flexible (grow / shrink the size of the
76
Advantages - Array based implementation

● Random access to elements are possible


● Quick access to elements are enabled

Disadvantages - Array based implementation

● Requires overestimated memory space,


which will be wastes at run time. (char
name[100];)
● Running time limitation will be there for
certain / most of the operations (Ex: 77
Array based implementation of List ADT
Problem Statement / Aim /
Objective
To implement the array based list ADT 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
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

if(s[i].data==d) //locate the data to be deleted


while(i<top){ //run the loop from the position of the data
to the end of list
s[i]=s[i+1]; //shift the elements in the next
position to the current position After deletion of element 8 in a list of of 5
elements (Array-based)
++i; 0 1 2 3 4 5 6 7
} 5 7
....
3
....
9 9
MAX-1

}
--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

1. Write an algorithm for inserting an element at the beginning in


the array based list ADT implementation.
2. Write an algorithm for inserting an element at a particular
position in the array based list ADT implementation.
3. Write an algorithm for deleting an element at the end in the array
based list ADT implementation.
4. Write an algorithm for deleting an element based on position in
the array based list ADT implementation. 88
the beginning in the array based list ADT
(Homework-14/08/2024)
void insertatfirst(int d) {
if(top == max-1) {
cout<<"Sorry, the list is full";
return;
}
for(int i=top; i>0; i--)
s[i+1]=s[i];

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

1. Write an algorithm to find the sum and average of all the


elements in an array-based list of ADT implementations.
2. Write an algorithm to replace all the odd numbers with 100 in the
array-based list ADT implementation.
3. Write an algorithm to square all the elements in the array-based
list ADT implementation.
4. Write an algorithm to clear all the elements in the array-based
list ADT implementation. 93
the elements in an array-based list ADT
(Homework-16/08/2024)
void sum_avg(){
int sum=0;
float avg;
if(top == -1){
cout<<"Sorry, the list is empty";
return;
}
for(int i=0;i<=top;i++)
sum=sum+s[i].data;
cout<<"\nThe sum of all the elements is: "<<sum;
avg=(float)sum/(top+1);
cout<<"\nThe average of all the elements is:"<<avg;
Code Courtesy:
} Niranjan M P
II ECE A
94
with 100 in the array based list ADT
(Homework-16/08/2024)
void oddval(){
if(top==-1) {
cout<<"List is empty";
return;
}
for(int i=0;i<=top;i++)
if(s[i].data%2!=0)
s[i].data=100;
}
Code Courtesy:
Sri Ram V
II ECE A
95
the array based list ADT (Homework-
16/08/2024)
void square(){
if(top==-1) {
cout<<"List is empty";
return;
}
for(int i=0;i<=top;i++)
s[i].data=(s[i].data*s[i].data);
} Code Courtesy:
Subbaiah C
II ECE A
96
4.Algorithm to clear all the elements in the
array based list ADT (Homework-16/08/2024)
void clear(){
if(top == -1) {
cout << "The list is already empty" << endl;
return;
}
for(int i = 0; i < max; i++) {
s[i].data = 0;
}
top = -1; Code Courtesy:
cout << "\nThe list has been cleared" << endl; Vijay S K
II ECE A
} 97
Homework - 19/08/2024
How many data fields are there in the data structure
used for implementing the following social media
platforms
1) Facebook
2) Twitter
3) LinkedIn
4) Whats App
5) Instagram
6) Google Maps
7) Quora 98
Homework - 19/08/2024
How many data fields are there in the data
structure used for implementing the following
social media platforms
1) Facebook - 97
2) Twitter - 70
3) LinkedIn - 48
4) WhatsApp - 39
5) Instagram - 41 Data Shared by:
6) Google Maps - 47 Niranjan M P
II ECE A
7) Quora - 48 99
Linked List-based
Implementation of List ADT

100
Linked list (Pointer based)
implementation of List ADT

● To avoid the linear (high) cost of insertion and


deletion in the array based implementation.
● Here list elements are not stored in contiguous
memory location.
● Linked list have sequence of data / structures /
nodes linked through pointers.
● Uses self-referential structure. They have collection
of elements in a structure (nodes).
● Each node in linked list has minimum of two fields
○ Data Field (Elements)
○ Address Field (Link for the other node)
Linked list (Pointer based)
implementation of List ADT
struct node{
int data; //store the data
struct node *next; //hold the address of the next node
Self-referential pointer
} (i.e., pointer for the same node/structure
itself)
● Member of the structure struct node *next; points
to the same node / structure itself. So, the name
linked list.
● Head pointer - Always points to the first node in the
linked list
● NULL pointer - It always indicates the end of the
linked list
● Last cell in the linked list (of the last node) have the
Advantages of Linked List
● Cost of insertion and deletion of elements in a
linked list is constant and its drastically low
compared to array based implementation.
● It reduces the processing / execution time of
certain vital algorithms.
● Its dynamic nature. We can allot memory on the go
and access the data accordingly.

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

1)Single Linked List


2)Double Linked List
3)Circular Linked List
i) Singly Circular Linked List
ii) Doubly Circular Linked List
106
Singly Linked list

Head Pointer NULL


Pointer
Doubly Linked list

X X

NULL NULL
Pointer Pointer
Head Pointer Tail
Pointer
Singly Circular Linked list

Head Pointer
Doubly Circular Linked list

Head Pointer Tail


Pointer
Single Linked List
Implementation of List ADT

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

//A node with multiple data


//A node with single data
struct node{
struct node{
int sno; //store the data
int data; //store the data
char name[10]; //store the data
struct node *next; //hold the address of next node
int rollno; //store the data
} float cgpa; //store the data
struct node *next; //hold the address of next
node

}
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

After inserting @ the First location as head


head=temp; New node
node
return; d
inserted as
head
X

}
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

1) Write an algorithm to count the number of nodes in a single


linked list ADT implementation.
2) Write an algorithm to find sum and average of elements in the
nodes of a single linked list ADT implementation.
3) Write an algorithm to find the minimum value nodes in a single
linked list ADT implementation.
4) Write an algorithm to find the maximum value nodes in a single
linked list ADT implementation. 121
single linked list ADT implementation.
(Homework-20/08/2024)
int countNodes(){
int count = 0;
if(head == NULL){
cout<<"Sorry, the list is empty";
return;
}
p= head;
while (p! =NULL){
count++;
p = p->next;
} Code Courtesy:
return count; Shara Jessil J
II ECE A
} 122
in single linked list ADT implementation.
(Homework-20/08/2024)
void sum_avg(){
int sum=0, count=0;
float avg;
if(head == NULL){
cout<<"Sorry, the list is empty";
return;
}
p=head;
while(p!=NULL) {
sum=sum+p->data;
p=p->next;
count++;
}
avg=(float)sum/count;
cout<<"\nSum is :"<<sum; Code Courtesy:
cout<<"\nAverage is :"<<avg; Steve Johnson Rathinam
} G
II ECE A
123
in a single linked list ADT implementation.
(Homework-20/08/2024)
int Minimum(){
if(head==NULL) {
cout<<"\nThe list is empty";
return;
}
p=head;
int mini=p->data;
while(p!=NULL) {
if(mini>p->data)
mini=p->data;
p=p->next; Code Courtesy:
} Hari Prasath M
II ECE A
return mini;
124
}
a single linked list ADT implementation.
(Homework-20/08/2024)
int maximum(){
if(head==NULL) {
cout<<"List is empty";
return;
}
p=head;
large=p->data;
while(p!=NULL){
if(large <p->data)
large=p->data;
p=p->next;
} Code Courtesy:
Subbaiah C
return large; II ECE A
} 125
Algorithm for deletion based on value in
a Single Linked List ADT
void deletedata(int d){
if(head==NULL){
cout<<"\nSorry the list is empty";
return; After the last iteration of while loop or
} after finding the data to be deleted
Node to be

p=head; deleted
d X
while(p->data!=d){ head tem
p
p p-
>next

temp=p; After deleting the node ‘p’


p=p->next;
} head tem
d
p p-
X

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

cout<<"\nSorry the list is


empty"; After deleting the head node

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

1) Write an algorithm to delete the last node in a single linked list


ADT implementation.
2) Write an algorithm to delete a node based on its position in a
single linked list ADT implementation.
3) Write an algorithm to insert a node at a particular position in a
single linked list ADT implementation.
4) Write an algorithm to clear the contents of a single linked list ADT
implementation. 129
1.Algorithm to delete the last node in a single linked list
ADT implementation.(Homework-22/08/2024)

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

1) Write an algorithm to swap the first and last node in a single


linked list ADT implementation.
2) Write an algorithm to square all the elements in a single linked
list ADT implementation.
3) Write an algorithm to swap the first and 4th node in a single
linked list ADT implementation.
4) Write an algorithm to remove the nodes with even numbers in a
single linked list ADT implementation. 134
1.Algorithm to swap the first and last node in a single
linked list ADT implementation.(Homework-23/08/2024)

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

//A node with multiple data


//A node with single data
struct node{
struct node{
int sno; //store the data
int data; //store the data char name[10];

struct node *next; int rollno;


//hold the address of next node

float cgpa;
struct node *prev;//hold the address of previous node
struct node *next; //hold the address of next node

struct node *prev; //hold the address of previous


} 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 insert(int d){


temp = new struct node;
temp->data=d;
temp->next=NULL;
temp->prev=NULL; During insertion of 1st node
if(head==NULL){ //if the list is empty During insertion of 2nd node
head = temp;
tail=temp; For insertion from 3rd node
return; onwards
}
p=head;
while(p->next!=NULL) //traverse till the end of the list
p=p->next; //gets traversed to the
next node in the list
p->next=temp;
temp->prev=p;
tail=temp; 144
Algorithm for displaying forward in Double 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.

● The analysis required to estimate the resources used


by an algorithm from the theoretical perspective ( in
terms of formule and expressions).
● A formal framework of notations (mathematical) will
be used for carrying out the algorithm analysis.
● They address both qualitative and quantitative
aspects of the algorithms.
● Further, they are also helpful to compute the
economical aspects of computational performance
of the algorithms.
What is to be analysed?

1) Running (Execution) time of the algorithm


Even though it differs based on computer configuration
(Processor, RAM, OS etc.,) we need to consider only
size or number of inputs (N) for algorithm analysis.
2) Memory (Space) occupied by the data in the
algorithm
Even though it differs based on computer configuration
(Processor, RAM, OS etc.,) we need to consider the
variables and the type / number of looping
Popular Notations for Algorithm
Analysis (Asymptotic notations)

1. Big Oh(O) - Upper bound (worst case )


2. Big Omega (Ω) - Lower bound (best case )
3. Big Theta (𝚯) - Two-way bound (average case )
4. Small / Little Oh(o) - Only upper bound (worst case
analysis )
5. Small Omega (⍵) - Rough estimate of the order of the
growth
6. Small Theta (𝝷) - Tight bound on the growth rate of
runtime of an algorithm.
Among the given notation Big Oh(O) plays a crucial role in
Time / Space / Resource complexity for
Big-Oh (O) notation
Big Oh Representation Name

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

● It defines the upper bound of the algorithm and the


defined function will not grow faster than the specified
limit.
● Used to access the worst case run time of the
algorithm and highly concerned with the larger
number of inputs (n)

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

● It defines the lower bound of the algorithm and the


defined function will not go below than the specified
limit.
● Used to access the best case run time of the
algorithm and highly concerned with the larger
number of inputs (n)

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

● It defines the average bound of the algorithm and the


defined function will not exceed or go below than the
specified limit.
● Used to access the average case run time of the
algorithm and highly concerned with the larger
number of inputs (n)

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++;

O(N3) - Since we have three nested loops running NxNxN times


Worst Case Run-time complexity of List ADT
Insertion Algorithms
ADT Type Insert @ Insert @ particular Insert @ End
beginning Position

Array based O(N) Find Pos: O(1) O(1)


Insert: O(N)
Single Linked O(1) Find Pos: O(N) O(N)
List
Insert: O(1)
Double Linked O(1) Find Pos: O(N) O(1)
List
Insert: O(1)
174
Worst Case Run-time complexity of List ADT
Deletion Algorithms
ADT Type Delete @ Delete @ particular Delete @ End
beginning Position

Array based O(N) Find Pos: O(1) O(1)


Delete: O(N)
Single Linked O(1) Find Pos: O(N) O(N)
List
Delete: O(1)
Double Linked O(1) Find Pos: O(N) O(1)
List
Delete: O(1)
175
Worst Case Run-time complexity of List ADT
Traversal / Search / Modify Algorithms
ADT Type Traversal Search Modify

Array based O(N) Pos: O(1) Search:


Value:O(N) O(1)/O(N)
update:O(1)
Single Linked O(N) Pos: O(N) Search:O(N)
List Value: O(N) update:O(1)

Double Linked O(N) Pos: O(N) Search:O(N)


List Value: O(N) update:O(1)
176
Worst Case Space complexity of List ADT

ADT Type Space Complexity

Array based O(N)

Single Linked List O(N)

Double Linked List O(N)

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

● Polynomial is a mathematical expression that consists of


variables and coefficients. Ex. X2+4x-3
● Implementing them are one of the popular
applications of List ADT.
● List ADT can be implemented for performing some
operations on polynomials.
● In the polynomial linked list, the coefficients and
power / exponents are the elements defined in the
nodes and they are linked to the next coefficient
through the address link to the next node.
Polynomial Linked list representation

Polynomial 1 : 4x5 + 7x3


+12x2+9x
P1 => List 1 4 5 7 3 12 2 9 1

Polynomial 2: 6x4 + 3x2 +9x


P2 => List 2 6 4 3 2 9 1

P3 => P1 + P2

Polynomial 3: 4x5 + 6x4+7x3 +15x2+18x


P3 => List 3 4 5 6 4 7 3 15 2 18 1
Node Initialization for polynomial list
struct node{
int coeff;
int pow;
struct node * next;
}*p1=NULL, *p2=NULL, *p3=NULL, *p=NULL;

*p1 = Polynomial 1 pointer


*p2 = Polynomial 2 pointer
*p3 = Polynomial 3 pointer
*p=Pointer for traversing in the linked list
Algorithm for Node Creation in
polynomial list
// Algorithm for creating nodes in polynomial list
void create_node(int x, int y, struct node **temp){
struct node *z;
z = *temp;
if(z == NULL){
p =(struct node*)malloc(sizeof(struct node));
*temp = p;
}
p->coeff = x;
p->pow = y;
p->next = (struct node*)malloc(sizeof(struct node));
p = p->next;
p->next = NULL;
}
Algorithm for Printing the polynomial from list
void printpolynomial(struct node *p){
while(p->next != NULL){
cout<<p->coeff<<”^”<<p->pow;
p = p->next;
if(p->next != NULL)
cout<<" + “;
}
}
Algorithm for Adding the polynomial from list (Cont…)
void polyadd(struct node *p1, struct node *p2, struct node
*p3){
while(p1->next && p2->next){
if(p1->pow > p2->pow){
p3->pow = p1->pow;
p3->coeff = p1->coeff;
p1 = p1->next;
}
else if(p1->pow < p2->pow){
p3->pow = p2->pow;
p3->coeff = p2->coeff;
p2 = p2->next;
}
Algorithm for Adding the polynomial from list (Cont…)
else {
p3->pow = p1->pow;
p3->coeff = p1->coeff+p2->coeff;
p1 = p1->next;
p2 = p2->next;
}
p3->next = (struct node *)malloc(sizeof(struct
node));
p3 = p3->next;
p3->next = NULL;
}
Algorithm for Adding the polynomial from list (Cont…)

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

Stack and Queue Data


Structures

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)Array based Implementation


● Size of the stack need to be defined (i.e.
its fixed)
● Only finite amount of elements could be
stored
● top==-1 (means stack is empty; i.e. stack
underflow)
● top == MAX-1 (means stack is full; i.e.
Array based implementation of Stack ADT
Problem Statement / Aim /
Objective
To implement the array based Stack ADT 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) 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

2) Linked List based Implementation


● Size of the stack need not be defined
( dynamic)
● We can hold infinite amount of elements
in the stack (subjected to size of RAM)
● top==NULL (means stack is empty; i.e.
stack underflow)
● Stack will not get filled to its maximum
Linked List based implementation of Stack ADT
Problem Statement / Aim /
Objective
To implement the linked list based Stack ADT 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) 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

void ModifyTOP(int newData){


if(isEmpty()){
cout<<"\nSorry stack is empty: Cannot
modify TOP";
return;
}
top->data = newData;
}
208
Worst Case Run-time complexity of Stack ADT
Algorithms

ADT Type PUSH POP Traversal Peek ModifyTop isEmpty/


isFull

Array O(1) O(1) O(N) O(1) O(1) O(1)


based

Single O(1) O(1) O(N) O(1) O(1) O(1)


Linked
List

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)Array based Implementation


● Size of the queue need to be defined (i.e.
its fixed)
● Only finite amount of elements could be
stored
● front==-1 and/or rear ==-1 (means
queue is empty; i.e. queue underflow)
● Rear == MAX-1 (means queue is full; i.e.
Array based implementation of Queue ADT
Problem Statement / Aim /
Objective
To implement the array based Queue ADT 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) 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

2) Linked List based Implementation


● Size of the Queue need not be defined
( dynamic)
● We can hold infinite amount of elements in
the Queue (subjected to size of RAM)
● front==NULL or rear==NULL (means
Queue is empty; i.e. Queue underflow)
● Queue will not get filled to its maximum
Linked List based implementation of Queue ADT
Problem Statement / Aim /
Objective
To implement the linked list based Queue ADT 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) 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

ADT Type Enqueu Deqeu Traver PeekFront/ ModifyFront/ isEmpty/


e sal PeekRear ModifyRear isFull

Array O(1) O(1) O(N) O(1) O(1) O(1)


based
Linked O(1) O(1) O(N) O(1) O(1) O(1)
List

222
Homework - 12/09/2024

https://classroom.google.com/c/NjkxNzYwNzI0MjYy/m/Njg1MzkyMzky
MDMz/details

1) Write a C++ program that pops the contents of


one stack and moves them to another stack using
linked list based Stack ADT
2) Write a C++ program that to merge the contents
of two stacks to a third stack using linked list
based Stack ADT 223
Homework - 13/09/2024
https://classroom.google.com/c/NjkxNzYwNzI0MjYy/m/NzA1OTA2NDU
3NTk4/details

1) Write a C++ program that pops the contents of a


stack and moves them to queue using linked list
based Stack/Queue ADT
2) Write a C++ program that to merge the contents
of two queues to a third queue using linked list
based Queue ADT

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.

Assume: you have already implemented separate algorithms for


PUSH and POP for both the stacks.

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.

Assume: you have already implemented separate algorithms


Option 2: for PUSH and
Option 1:
POP for the three stacks.
In a single PUSH and POP
functions, pass the stack reference
as an additional argument
Void PUSH1(int d); //Algorithm to push in stack1
Void PUSH2(int d); //Algorithm to push in stack2
(top1/top2/top3)
Void PUSH3(int d); //Algorithm to push in stack3
Int POP1(); // Algorithm for POP from stack1
Int POP2(); .//Algorithm for POP from stack2
Int POP3(); .//Algorithm for POP from stack3

229
Ex 4: Concatenate two strings using stack

● Create char[] to store a string.


● Create two Stacks with two different strings.
● Push the characters of each string, one by one to each stack.
● Pop all characters from stack1, one by one and push to stack3
● Pop all characters from stack2, one by one and push to stack3
● Pop all characters from stack3, one by one and put into the
char[].
● Finally, convert to the String.

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)

Infix Expression Postfix


1)A + B + C Expression
2)A * (B+C) 1)ABC++
3)(A/B) * C 2)ABC+*
4)[(5+8)-4]*3 3)AB/C*
5)6*{[5+ 4)58+4-3*
[(2*3)+8]]-3} 5)6523*8++3-*
233
Ex. 7 Postfix Expression Evaluation (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

Tree Data Structures

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

Insert the following sequences in a BST and


perform all four types of traversals.
1. G, H, F, D, A, B, S, X, O, Q
2. 45, 12, 3, 6 ,75, 12, 14, 56
3. M, P, X, O, Q, F, D, R, G, A, K
4. 20,17,23,14,32,8,12,41,6,9,13
5. Pen, Laptop, Book, Mug, Note, Chair, Phone,
Earpod
252
Binary Search Tree implementation
Problem Statement / Aim /
Objective
To implement the Binary Search 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 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

struct node* createnode(int d){


temp= new struct node;
temp->data=d;
temp->left=NULL;
temp->right=NULL;
return temp;
} 255
Algorithm for Insertion in a BST
struct node* insert(struct node *T, int d){
if(T==NULL)
T=createnode(d);
else if(d>T->data)
T->right=insert(T->right,d);
else if(d<T->data)
T->left=insert(T->left,d);
return T;
} 256
Algorithm for Preoder Traversal

void preorder(struct node *T){


if(T!=NULL){
cout<<T->data; //M
preorder(T->left); //L
preorder(T->right); //R
}
}
257
Algorithm for Postorder Traversal
void postorder(struct node *T){
if(T!=NULL){
postorder(T->left); //L
postorder(T->right); //R
cout<<T->data; //M
}
}

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

void decendingorder(struct node* T){


if(T!=NULL){
decendingorder(T->right); //R
cout<<T->data;
//M
decendingorder(T->left);
//L
}
} 260
Homework - 26/09/2024
h
ttps://classroom.google.com/c/NjkxNzYwNzI0MjYy
/m/NzA2NTc2ODUzOTM2/details
In the above Binary Search Tree (BST) code
implement the following algorithms:
1) Square all the elements in the nodes of the tree.
2) Find the sum of all the elements in the nodes of the
tree.
3) Find the maximum element in the tree. 261
Algorithm for Finding the Minimum Element node

struct node *minimum(struct node*


T){
while(T->left!=NULL)
T=T->left;
return T;
} 262
Algorithm for Finding the Maximum Element node

struct node *maximum(struct node* T)


{
while(T->right!=NULL)
T=T->right;
return T;
} 263
Algorithm for Deletion in BST
struct node *Delete(struct node *T, int d){
//First search the node to be deleted
if (T==NULL)
return T;
else if(d>T->data)
T->right=Delete(T->right,d);
else if(d<T->data)
T->left=Delete(T->left,d);
//Node to be deleted have been located at this point
- Now delete
else{ //Case 1: 0 child
if(T->left ==NULL && T->right ==NULL){
T=NULL;
delete T;
}
Algorithm for Deletion in BST Cont…
//Case 2: 1 child (right child only)
else if(T->left==NULL ){
temp=T;
T=T->right;
delete temp;
}
//Case 2: 1 child (left child only)
else if(T->right==NULL ){
temp=T;
T=T->left;
delete temp;
}
Algorithm for Deletion in BST Cont…
//Case 3: 2 children (i.e T->left !=NULL && T->right!
+NULL)
else {
temp=minimum(T->right); //find min element node
in right subtree
T->data=temp->data; //duplicate the data
node to be removed
//Now the problem will be reduced to case 1 or case 2
//Now remove the duplicate element by calling the
algorithm again
T->right=Delete(T->right,T->data);
}
}
return T;
}
Algorithm for Searching in BST

struct node *Search(struct node *T, int d)


{
if (T == NULL || T->data == d)
return T;
if (d > T->data)
return Search(T->right, d);
else
return Search(T->left, d);
} 267
Run time and Space Complexity of BST
Algorithms

Complexity Search Insert Delete Traversal

Worst case O(N) O(N) O(N) O(N)

Average case O(log N) O(log N) O(log N) O(N)

Best case O(1) O(log N) O(log N) O(N)


Expression Trees

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

● AVL Trees are named after Adelson, Velskii and


Landis
● AVL Trees are balanced BST.
● Drawback of BST: Based on the sequence of
inputs the tree may not be balanced under few
cases (Ex:Skew Trees)
● AVL Trees converts such input sequences into
balanced trees.
● Unbalanced conditions are observed from the
Balance Factor
● Balance Factor = Height of left subtree - Height of
right subtree

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

To make the AVL Tree balanced, rotation of the nodes need


to be done on every insertion. This makes 4 different cases
1) Left Left (Perform Single Rotation with Right (SRR) )
2) Right Right (Perform Single Rotation with Left (SRL) )
3) Left Right (Perform Double Rotation SRL + SRR)
4) Right Left (Perform Double Rotation SRR + SRL)
Left Left Case

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

struct node* createnode(int d){


temp= new struct node;
temp->data=d;
temp->left=NULL;
temp->right=NULL;
temp->height = 0;
return temp; 283
Algorithm to return height of a node
int height (struct node *T){
if (T==NULL)
return 0;
return (T->height);
}

Algorithm to return height of a tree


int max(int a, int b){
return (a>b)?a:b;
} 284
Single Rotation with Left (SRL)
BF=-2
y
x
Single Rotation
y x
with Left(SRL)

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

Complexity Search Insert Delete Traversal

Worst case O(log N) O(log N) O(log N) O(N)

Average case O(log N) O(log N) O(log N) O(N)

Best case O(1) O(log N) O(log N) O(N)

292

End of Unit - III

293
UNIT - IV

Disjoint Sets and Graphs

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

1)Makeset - Form / Construct a set / subset


of elements or data
2)Find Set - Given a partiular element /
data, it lets you to identify, that it belongs
to which set / subset.
3)Union - Merge two subsets into a single
set
Implementation / Representation of
Disjoint Sets

● Linked-List Based Disjoint


Sets
● Tree Based Disjoint Sets
List Based Disjoint Sets
● Each Set references list of items in the
set
● Each item / data references the the set
the element is present
● Union operation is slower.
Linked List Based Disjoint Sets
Tree Based Disjoint Sets
● Each set / subset is maintained in a
tree
● Here disjoint set form a forest
● Root node will be the representative
node
● Union operation will be faster
(depending on the time taken for find
operation)
Tree Based Disjoint Sets
Implementation of Disjoint Sets
(Tree-based Implementation)

1. Union by Rank (Smart Union


Algorithm)
2. Path Compression Approach
Homework - 18/10/2024
Implement Tree based disjoint set on the
sequence of even numbers from 0 to 18.
Implement the union operations on the numbers
which are multiples of 3 and 4 sequentially one
after another. Union (4,6), Union (6,8), Union
(8,12), Union (12,16), Union (16,18). Implement
the same using
i) Union by Rank
ii) Path Compression 306
Union by Rank
To optimize the Union operation by ensuring that the smaller
tree is always attached to the root of the larger tree.
Prevents the trees from becoming too imbalanced, which
would lead to inefficient find operations.
Algorithm Steps for Union by Rank:
● Find the representatives (root elements) of the sets
containing elements x and y.
● If the representatives are the same, return it.
● If the rank of the representative of x is greater than the
rank of the representative of y, make y's representative
point to x's representative and update the rank of x's
representative or vise versa. 307
Path Compression

● Time taken by the Find and Union Algorithm of


Smart Union (Union by Rank) approach is huge
● Since, the length of the tree (path) grows on each
union operation in the union by rank approach,
path compression is required.
● The path compression approach reduces the path
by directly linking the elements to the root node of
the tree.
● So, the time complexity of the path compression
algorithm is drastically reduced.
Path Compression
It reduces the height of the trees in the Union-Find data
structure.
It aims to flatten the paths during the find operation, resulting
in shorter paths for subsequent operations.
Algorithm Steps for Path Compression:
● Find the representative (root element) of the set containing
element x.
● While traversing the path from x to its representative, make
each visited element directly point to the representative.

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

Complexity Makeset Find Union Link

Worst case O(1) Union by Rank - O(N) O(1) O(1)


Path compression - O(1)

Average case O(1) Union by Rank - O(Log N) O(1) O(1)


Path compression - O(1)

Best case O(1) Union by Rank - O(1) O(1) O(1)


Path compression - O(1)

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

Graph: A Graph G=(V,E) has set of vertices and


edges
Vertices: Each node in a graph
Edge: Pair of vertices (v1,v2), that belongs to V
Path: Sequence of vertices v1,v2,....Vn
Length: Number of edges on the path
Loop: A path from the verte v1 to itself
A Graph G=(V,E) can have a maximum of V (V-
Cyclic and Acyclic Graph
Cycle: A directed graph with atleast one
path from v1 to itself through other vertices
v2….,vn and forms a loop.
Acycle: A directed graph that does not form
a loop or cycle (Directed Acyclic Graph)
Types of Graphs

● Weighted Graphs ● Weighted Directed Graphs


● Unweighted Directed Graphs
● Unweighted
● Directed Unweighted Graphs
Graphs ● Undirected Weighted Graphs
● Directed Graphs ● Directed Cyclic Graphs
○ Cyclic Graphs ● Directed Acyclic Graphs
○ Acyclic Graphs ● etc.,
● Undirected Graphs
Types of Graphs

323
Graph Representation

324
Representation of Graphs

1. Adjacent Matrix Representation


A simple 2D representation of a graph is
possible with the support of matrices
2. Adjacent List Representation
A simple single linked list representation of
a graph is possible by linking the associated
vertices and edges
Representation of Graphs

Adjacency Matrix Adjacency List


A Graph
Representation Representation

326
Graph Traversals

327
Traversal in Graphs
Depth First Search (DFS)
● Implementation using Recursive
algorithms or Stack ADT

Breadth First Search (BFS)


● Implementation using Queue ADT
Depth First Search (DFS)
Steps to implement DFS traversal...
Step 1 - Define a Stack of size total number of vertices in the graph.
Step 2 - Select any vertex as starting point for traversal. Visit that vertex and push it on to the Stack.
Step 3 - Visit any one of the non-visited adjacent vertices of a vertex which is at the top of stack and
push it on to the stack.
Step 4 - Repeat step 3 until there is no new vertex to be visited from the vertex which is at the top of
the stack.
Step 5 - When there is no new vertex to visit then use back tracking and pop one vertex from the
stack.
Step 6 - Repeat steps 3, 4 and 5 until stack becomes Empty.
Step 7 - When stack becomes Empty, then produce final spanning tree by removing unused edges
from the graph
329
Breadth First Search (BFS)
Steps to implement BFS traversal...

Step 1 - Define a Queue of size total number of vertices in the graph.

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 5 - Repeat steps 3 and 4 until queue becomes empty.

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

Hashing, Sorting Algorithms


and Case Study

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

● Hashing operations are carried out to store the data


in a hash table.
● It follows the operations based on the hash function
to compute the address (index) for storing the data
in the hash table.
Key terminologies associated:
● Hash function
● Hash Table
● Hashing
Hash Function

A hash function h(N) maps keys / bigger data / strings to a smaller


integer value between the interval {0, N-1} - i.e, the size of the hash
table.

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

● Collisions occur when different elements are trying to get


mapped to the same cell in the hash table.
● It could be avoided using:
1) Separate Chaining - uses the concept of linked list
2) Open Addressing - looks for alternate empty cells for insertion
a) Linear probing
b) Quadratic probing
c) Double hashing
Homework - 26/10/2024
Apply the following 4 methods to avoid collision on the
following data with table size of 8.
14, 24, 32, 17,12, 41, 26
1) Separate Chaining
2) Open Addressing
a) Linear probing
b) Quadratic probing
c) Double hashing

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 linear probing
Open Addressing - Quadratic Probing Method

● Eliminates the primary clustering problem of linear


probing.
● The popular choice of finding cells by f(i) = i 2
● Load Factor = Number of items / Array Size
● To avoid clusters, the load factor should be minimum.
● In quadratic probing steps are square of the index (output
of hash function)
● If index is x, then the probing entries on the hash table will
be
● 2 2, 2 ….
Open Addressing - Quadratic 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

● Chose const , R as a small prime number.


● Let R = 7, so we are considering table as 7
● hash2(x) = R - (x mod R)
Rehashing

● The process of extending the hash table size,


particularly in the open addressing (linear
probing, quadratic or double hashing) method
of collision avoidance.
● If the load factor exceeds beyond unity, (i.e no.
of elements exceeds table size), the hash
table size needs to be extended with a value
(prime number) less than existing table size.
364
Rehashing
● Rehashing is the process of extending the hash
table size.
● Rehashing means hashing again.
● They are extended based on the chosen prime
number
● Following this process, again the hashing will be
performed with the new table size and hash
function
● Rehashing is also done if the load factor is
greater than the predefined value.
● When the load factor increases, which implies
that the time complexity also increases as
Separate Chaining

366
Separate Chaining

● Separate chaining is a collision avoidance


technique to store elements in a hash table, which
is represented as an array of linked lists.
● Here, each index in the table is a chain of
elements mapping to the same hash value.
● When numerous elements are hashed into the
same slot index, those elements are added to a
chain, which is a singly-linked list.
Implementation of Open
Addressing (Linear Probing)

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)

// Display the Hash Table Contents


void display() {
cout<<"\nIndex \t Value";
for (int i = 0; i < tablesize; i++) {
cout<<"\n<<i<<”\t”;
if (table[i].data != -1)
cout<<table[i].data;
}
cout<<endl;
} 371
Deletion 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

//Hash Function Implementation


int hash(int key){
return (key%tablesize);
}

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

struct node* find(int key){


p=table[hash(key)];
while(p!=NULL && p->data!=key)
p=p->next;
return p;
}
Display the contents of Hash Table

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

Worst case Analysis


Collision Insertion Deletion Search
Avoidance
Open Addressing O(N) O(N) O(N)
Separate Chaining O(1) O(N) O(N)
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 384
Sorting Algorithms

385
Sorting

● Sorting refers to the process of arranging


elements in a specific order, often in ascending or
descending order based on some criteria.

● It is a fundamental operation in computer science


and is used in various applications such as data
analysis, searching, and more.
386
Bubble 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

-It's useful for educational purposes and small datasets


388
389
Algorithm: Bubble Sort
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n -1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
} 390
Time complexity

Worst case: o(n^2)In all the cases


two loops will
be executed…
Average case:o(n^2)

Best case:o(n^2)
1st optimized version

void bubbleSort(int arr[], int n) {


for (int i = 0; i < n - 1; i++) {
for (int j = 0; j < n -i-1; j++) {
if (arr[j] > arr[j + 1]) {
int temp = arr[j];
arr[j] = arr[j + 1];
arr[j + 1] = temp;
}
}
}
}
Time complexity
Worst case: o(n^2)
In all the
cases two
Average case:o(n^2)loops will be
executed…

Best case:o(n^2)
2nd optimized version
void bubbleSort(int arr[], int n) {

int flag; // If no swap is made in a


for (int i = 0; i < n - 1; i++) {
pass, array is already
sorted, break out of the
flag = 0; // Initialize flag to 0 for each pass
loop
for (int j = 0; j < n - i - 1; j++) {
if (flag == 0)
if (arr[j] > arr[j + 1]) {
break;
int temp = arr[j];
}
arr[j] = arr[j + 1];
}
arr[j + 1] = temp;

flag = 1; // Set flag to 1 if a swap is made

}
Animation

Bubble sort animation

Example array: 16,14,5,6,8


Worst Case Run-Time complexity of Bubble Sort

Worst case: O(n^2)


If the array is
already
Average case:O(n^2)
sorted,then the
best case will be
O(n)

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

● Begin with second element and


compare it with the first.
● Insert the second element into its
correct position.
● Continue this process for each
element , expanding the sorted
portion of the array with each
iteration.

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

Worst case: O(n^2)


If the array is
already
Average case:O(n^2)
sorted,then the
best case will be
O(n)

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.

● Extract Max/Min : Removes the maximum or minimum


element form the heap and returns it.

● Heapify : Converts an arbitrary binary tree into a heap.

408
Heapify Algorithm

void heapify(int arr[], int n, int i) { // If largest is not root

int largest = i; // Initialize largest as if (largest != i) {


root int temp = arr[i];
int left = 2 * i + 1; // left child = 2*i + arr[i] = arr[largest];
1 arr[largest] = temp;
int right = 2 * i + 2; // right child = 2*i
+2 // Recursively heapify the affected
sub-tree
// If left child is larger than root
heapify(arr, n, largest);
if (left < n && arr[left] > arr[largest]) }
largest = left; } 409
Heap Sort Algorithm
//Heap sort Algorithm
void heapSort(int arr[], int n) {
int i;
for ( i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for ( i = n - 1; i > 0; i--) {
// Move current root to end
int temp = arr[0];
arr[0] = arr[i];
arr[i] = temp;
// call max heapify on the reduced heap
heapify(arr, i, 0);
}
} 410
Worst Case Run-Time complexity of Heap Sort

Worst case: O(N Log N)

Average case:O(N Log N)

Best case:O(N Log N)


Applications of Heap Sorting

● Heaps are commonly used to implement priority


queues, where elements are retrieved based on
their priority (maximum or minimum value).
● Heapsort is a sorting algorithm that used a heap
to sort an array in ascending or descending order.
● Heaps are used in graph algorithms like Dijkstra’s
algorithm for finding the shortest paths and
minimum spanning trees.

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

● Pick: Select a pivot element.

● Divide: Split the problem set, move smaller parts to


the left of the pivot and larger items to the right.

● Repeat and combine: Repeat the steps and combine


the arrays that have previously been sorted.

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

● Consider: arr[] = {10, 80, 30, 90, 40}.


● Compare 10 with the pivot and as it is
less than pivot arrange it accordingly.

417
Example

● Compare 80 with the pivot. It is


greater than pivot.

418
Example

● Compare 30 with pivot. It is less than


pivot so arrange it accordingly.

419
Example

● Compare 90 with the pivot. It is


greater than the pivot.

420
Example

● Initial partition on the main array

421
Example

● Arrange the pivot in its correct


position.

422
Example

● Partitioning of the subarrays:

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);

// Separately sort elements before partition and after


partition
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
425
Swap and Print Algorithm

void swap(int* a, int* void printArray(int arr[], int


b) { size) {

int t = *a; for (int i = 0; i < size; i++)

*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.

Average Case: θ ( N log (N))

● Quicksort’s average-case performance is usually very good in practice, making it one


of the fastest sorting Algorithm.

Worst Case: O(N^2)

● 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

(Randomized Quicksort ) to shuffle the element before sorting.

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

Sorting Worst Case Avg Case Best Case

Bubble O(N2) O(N2) O(N)


Insertion O(N2) O(N2) O(N)
Merge Sort O(N Log N) O(N Log N) O(N Log N)
Quick Sort O(N2) O(N Log N) O(N Log N)
for worst choice of pivot

Heap Sort O(N Log N) O(N Log N) O(N Log N)



End of Unit - V

433

Thank You!

434
434

You might also like