0% found this document useful (0 votes)
18 views

ADL Lab (A8513) Manual

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

ADL Lab (A8513) Manual

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

VARDHAMAN COLLEGE OF ENGINEERING

(AUTONOMOUS)
Affiliated to JNTUH, approved by AICTE, Accredited by NAAC with A++
Grade ISO 9001:2015 Certified
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India

Laboratory Manual
Advanced Data Structures
Laboratory
(II B. Tech- I SEMESTER)
(VCE-R22)
Course Code-A8513
Course Lead- Dr. S.V. Vasantha

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

VARDHAMAN COLLEGE OF ENGINEERING


(AUTONOMOUS)
Kacharam, Shamshabad, Hyderabad – 501218, Telangana, India
1
VCE-R22 ADS LAB
PROGRAM OUTCOMES (POS)
PO1: Engineering Knowledge: Apply knowledge of mathematics, science,
engineering fundamentals and an engineering specialization to the solution complex
engineering problems.
PO2: Problem Analysis: Identify, formulate, research literature and analyze complex
engineering problems reaching substantiated conclusions using first principles of
mathematics, natural sciences and engineering sciences.
PO3: Design/ Development of Solutions: Design solutions for complex engineering
problems and design system components or processes that meet specified needs
with appropriate consideration for public health and safety, cultural, societal and
environmental considerations.
PO4: Conduct investigations of complex problems:Use research-based knowledge
and research methods including design of experiments, analysis and interpretation
of data and synthesis of information to provide valid conclusions.
PO5: Modern Tool Usage: Create, select and apply appropriate techniques,
resources and modern engineering and IT tools including prediction and modeling to
complex engineering activities with an understanding of the limitations.
PO6: The Engineer and Society:Apply reasoning informed by contextual knowledge
to assess societal, health, safety, legal and cultural issues and the consequent
responsibilities relevant to professional engineering practice.
PO7: Environment and Sustainability: Understand the impact of professional
engineering solutions in societal and environmental contexts and demonstrate
knowledge of and need for sustainable development.
PO8: Ethics:Apply ethical principles and commit to professional ethics and
responsibilities and norms of engineering practice.
PO9: Individual and Team Work:Function effectively as an individual, and as a
member or leader in diverse teams and in multi-disciplinary settings.
PO10: Communication: Communicate effectively on complex engineering activities
with the engineering community and with society at large, such as being able to
comprehend and write effective reports and design documentation, make effective
presentations and give and receive clear instructions.
PO11: Project Management and Finance:Demonstrate knowledge and
understanding of engineering and management principles and apply these to one’s
own work, as a member and leader in a team, to manage projects and in
multidisciplinary environments.
PO12: Life-long Learning:Recognize the need for and have the preparation and
ability to Engage in independent and life- long learning in the broadest context of
technological Change.
PROGRAM SPECIFIC OUTCOMES (PSOs)
PSO1: To collect requirements, analyze, design, implement and test software
Systems.
PSO2:To analyze the errors and debug them within minimal time.
2
VCE-R22 ADS LAB
COURSE OVERVIEW:
Advanced Data Structures Laboratory course is to improve the programming skills using
CLanguage.This course covers implementing applications of linked lists and queues.
Thiscourse also enables to implement search trees and graphs , dictionaries and
hashing.Thecourse also enables to implementadvanced search tress and text processing.
After the completion of this course student will be able to implement efficient algorithm for
a software.

COURSE OUTCOMES (COs)

After the completion of the course, the student will be able to:
CO# Course Outcomes

Implement programs using linear data structures to process data.


A8513.1

A8513.2 Implement operations on non-linear data structures for handling large data.
A8513.3 Build traversal algorithms for efficient search on nonlinear data structures.
A8513.4 Develop algorithms for text processing applications.

BLOOM’SLEVELOFTHECOURSE OUTCOMES

Bloom’sLevel
CO# Remember Understand Apply Analyze Evaluate Create
(L1) (L2) (L3) (L4) (L5) (L6)
A8513.1 ✔
A8513.2 ✔
A8513.3 ✔
A8513.4 ✔

COURSEARTICULATIONMATRIX
PO10

PO11

PO12

PSO1

PSO2
PO1

PO2

PO3

PO4

PO5

PO6

PO7

PO8

PO9

CO#/
POs

A8513.1 3 1 2 2 2

A8513.2 3 2 2 2 2

A8513.3 3 2 2 2 2

A8513.4 2 2 3 2 2
Note:1-Low,2-Medium,3-High

3
VCE-R22 ADS LAB
ASSESSMENT SCHEME R22
Max. Marks
S.NO# EVALUATION METHOD ASSESSMENT TOOL
Marks Total

A write-up on day-to-day experiment in


10
the laboratory
Viva-voce (or) tutorial (or) case study (or)
application (or) poster presentation of 10
Continuous Internal the course
Evaluation (CIE)
1 40
Internal practical examination 10

Laboratory Project, which consists of the


Design (or) Software / Hardware Model
10
Presentation (or) App Development (or)
Prototype Presentation
Write-up 10

Experiment/program 15

Semester End Evaluation of results 15


2 60
Examination (SEE)
Presentation on another
10
experiment/program
Viva-Voce 10

4
VCE-R22 ADS LAB
LAB SESSION PLAN

CO BLOOM’s
No Title of the Experiment
LEVEL
write a C program to implement Circular Linked CO-1 L3
1
Lists
write a C program to implement circular queue CO-1 L3
2
using linked list
write a C program to implement deque using linked CO-1 L3
3
list
write a C program to implement addition of two CO-1 L3
4
polynomials
write a C program to implement multiplication of CO-1 L3
5
two polynomials
6 write a C program to implement Heap Sort CO-2 L3
7 write a C program to implement Binary search trees CO-2 L3
– operations: insertion, deletion,searching and
traversal
8 write a C program to implement Breadth First CO-3 L3
Search (BFS)
9 write a C program to implement Depth First Search CO-3 L3
(DFS)
10 write a C program to implement AVL Tree, CO-2 L3
Operations – Insertion, Deletion and Searching
write a C program to implement Dictionaries CO-2 L3
11

Implementation of Hash Table with linear probing CO-1 L3


12

13 write a C program to implement Brute-Force CO-4 L3


Pattern Matching , Boyer- Moore Algorithm
14 write a C program to implement Knuth-Morris-Pratt CO-4 L3
Algorithm

5
VCE-R22 ADS LAB
Introduction
Circular Linked Lists: Circular Linked Lists are an extension of the traditional
linked list data structure. In this variant, the last node in the list points back
to the first node, forming a circular loop. This arrangement facilitates
seamless traversal from any point in the list to any other point, making it
particularly useful for scenarios where cyclic operations or continuous data
processing is required. Circular Linked Lists find applications in tasks such as
managing resources in a round-robin scheduling system or representing
cyclic structures in real-world scenarios.

Circular Queue using Linked List: A Circular Queue is a data structure that
follows the First-In-First-Out (FIFO) principle. When implemented with a
linked list, it allows for efficient management of a dynamic collection of
elements. The circular arrangement eliminates the need to shift elements
during enqueue and dequeue operations, providing a more optimized
solution. Circular Queues are employed in scenarios where a continuous
flow of data is desired, such as in network traffic buffering or job scheduling
in operating systems.

Deque using Linked List: Deque, short for double-ended queue, is a


versatile data structure that supports insertion and deletion at both ends.
When implemented with a linked list, it offers flexibility in managing data at
the front and rear ends efficiently. Deques find applications in situations
where dynamic and bidirectional data manipulation is essential, such as in
undo mechanisms in applications or managing a sliding window of data in
algorithms.

Addition of Two Polynomials: Polynomial addition involves combining like


terms from two polynomials by adding coefficients corresponding to the
same power of the variable. This operation is fundamental in algebraic
computations, including signal processing and cryptography. Implementing
polynomial addition efficiently is crucial for handling large datasets and
complex mathematical expressions.

Multiplication of Two Polynomials: Polynomial multiplication is the process


of multiplying each term of one polynomial by every term of the other. This

6
VCE-R22 ADS LAB
operation is pivotal in diverse fields, including computer graphics, error
correction codes, and numerical simulations. Efficient implementation of
polynomial multiplication using data structures like linked lists is essential
for optimizing computational resources and ensuring accurate results.

Heap Sort: Heap Sort is a comparison-based sorting algorithm that


leverages a binary heap data structure. By creating a heap and repeatedly
extracting the maximum element, Heap Sort achieves efficient sorting with
a consistent time complexity. This algorithm is widely used in scenarios
where a stable sorting solution is not critical, such as in embedded systems
or real-time applications.

Binary Search Trees: Binary Search Trees are hierarchical data structures
where each node has at most two children. The left child contains values
smaller than the node, while the right child contains values greater than the
node. Operations on Binary Search Trees include insertion, deletion,
searching, and traversal. These trees are employed in scenarios where
maintaining a sorted dataset and efficient search operations are paramount,
such as in database indexing or symbol tables in compilers.

Breadth First Search (BFS): Breadth First Search is a graph traversal


algorithm that explores all vertices at the current depth before moving on to
the next level. This algorithm is invaluable in applications such as social
network analysis, shortest path calculations, and network routing protocols.
BFS efficiently covers the breadth of a graph, making it suitable for scenarios
where a comprehensive exploration of the structure is required.

Depth First Search (DFS): Depth First Search is a graph traversal algorithm
that explores as far as possible along each branch before backtracking. DFS
is utilized in diverse applications, including maze solving, topological sorting,
and cycle detection in graphs. This algorithm provides insights into the
structure of a graph and is often chosen based on specific problem
requirements.

AVL Tree, Operations – Insertion, Deletion, and Searching: AVL Trees are
self-balancing binary search trees that ensure logarithmic height, resulting
in efficient searching, insertion, and deletion operations. The AVL Tree's

7
VCE-R22 ADS LAB
balancing mechanism involves rotations during updates to maintain optimal
performance. These trees are applied in scenarios where consistent and
reliable search and update operations are essential, such as in database
management systems or filesystems.

Dictionaries: Dictionaries are key-value data structures that facilitate


efficient insertion, deletion, and searching of elements. Used in a variety of
applications, dictionaries provide a means to organize and retrieve data
based on unique keys. Implementing dictionaries effectively is crucial for
tasks like spell-checking algorithms, language processing tools, and real-
time data caching systems.

Hash Table with Linear Probing: Hash Tables utilize a hash function to map
keys to indices. Linear probing is a collision resolution technique where, in
the event of a collision, the colliding element is placed in the next available
slot. This implementation ensures efficient retrieval of values associated
with keys, making hash tables with linear probing suitable for scenarios
where collision resolution needs to be handled with simplicity and
efficiency.

Brute-Force Pattern Matching, Boyer-Moore Algorithm: Brute-Force


Pattern Matching involves comparing a pattern with all substrings of a text,
providing a straightforward but potentially less efficient approach. The
Boyer-Moore Algorithm improves efficiency by strategically skipping
unnecessary character comparisons, making it suitable for large-scale
pattern matching applications. These algorithms are used in tasks like text
searching, DNA sequence analysis, and data mining.

Knuth-Morris-Pratt Algorithm: The Knuth-Morris-Pratt Algorithm is a linear-


time pattern matching algorithm that efficiently searches for occurrences of
a pattern in a text. By avoiding unnecessary character comparisons through
the use of information about previously matched characters, KMP provides
an optimized approach to pattern matching. Widely used in applications like
string matching and data compression, the KMP Algorithm is an essential
tool in computer science and information retrieval.

8
VCE-R22 ADS LAB
Write a C program to implement Circular Linked
Week-1
Lists

1. How does a Circular Linked List differ from a traditional linked


Pre-Lab list?
2. What are the key steps involved in representing nodes in a
Questions Circular Linked List?
3. How will you ensure that the last node points back to the first
node, creating a circular structure?
4. What test cases do you plan to use to verify the correctness of
your Circular Linked List implementation?

#include <stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
}*head=NULL,*last,*newnode,*p,*prev;
void create();
void display();
void insbeg();
void insmid();
void insend();
void del();
void delbeg();
void main()
{
create();

9
VCE-R22 ADS LAB
insbeg();
display();
insend();
insmid();
display();
delbeg();
display();
del();
display();
}
void create()
{
int i,n;
printf("Enter the no of nodes\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data\n");
scanf("%d",&newnode->data);
if(head==NULL)
head=newnode;
else
last->next=newnode;
last=newnode;
last->next=head;

10
VCE-R22 ADS LAB
}
}
void display()
{
if(head==NULL)
printf("Circular linked list is empty\n");
else
{
p=head;
printf("The elements are");
do
{
printf("%3d",p->data);
p=p->next;
}while(p!=head);
printf("\n");
}
}
void insbeg()
{
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data to insert");
scanf("%d",&newnode->data);
newnode->next=head;
last->next=newnode;
head=newnode;

11
VCE-R22 ADS LAB
}
void insend()
{
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data to insert");
scanf("%d",&newnode->data);
newnode->next=head;
last->next=newnode;
last=newnode;
}
void insmid()
{
int pos,i;
printf("Enter the position to insert\n");
scanf("%d",&pos);
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the data to insert");
scanf("%d",&newnode->data);
p=head;
for(i=2;i<pos;i++)
p=p->next;
newnode->next=p->next;
p->next=newnode;
}
void delbeg()
{

12
VCE-R22 ADS LAB
p=head;
last->next=head->next;
head=head->next;
free(p);
}
void del()
{
int pos,i;
if(head==NULL)
printf("List is empty\n");
else if(head==last&&head!=NULL)
{
p=head;
head=last=NULL;
free(p);
}
else
{
printf("Enter the position to delete\n");
scanf("%d",&pos);
p=head;
if(pos==1)
{
head=head->next;

last->next=head;
free(p);

13
VCE-R22 ADS LAB
}

for(i=1;i<pos;i++)
{
prev=p;
p=p->next;
}
if(p->next==head)
last=prev;
prev->next=p->next;
free(p);
}
}
Output:
Enter the no of nodes
3
Enter the data
4
Enter the data
5
Enter the data
2
Enter the data to insert1
The elements are 1 4 5 2
Enter the data to insert6
Enter the position to insert

14
VCE-R22 ADS LAB
4
Enter the data to insert8
The elements are 1 4 5 8 2 6
The elements are 4 5 8 2 6
Enter the position to delete
3
The elements are 4 5 2 6
1. Did the implementation successfully create and manage Circular
Linked List?
2. How did the insertion and deletion operations perform in the
Circular Linked List?
3. Were there any considerations or challenges related to the
Post-Lab traversal in a circular structure?
Questions 4. What is time and space complexity of algorithm?
5. What insights did you gain from implementing a Circular Linked
List in C?
6. What enhancements or additional features could be considered
for future iterations of the Circular Linked List program?
7. Give any suitable application using this data structure.

15
VCE-R22 ADS LAB
Write a C program to implement circular queue
Week-2
using linked list

1. What is a queue?
Pre-Lab 2. What are the major differences between circular queue and a
linear queue?
Questions
3. State reasons for selecting circular queue over linear queue in
some applications.
4. Explain the basic operations of a circular queue.
5. How a circular queue is implemented using arrays?

#include <stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *next;
}*front=NULL,*rear=NULL,*newnode,*temp;
void enqueue(int);
void display();
void dequeue();
void first();
void last();
void main()
{
enqueue(34);
enqueue(10);
enqueue(23);
display();
dequeue();
16
VCE-R22 ADS LAB
first();
last();
}
void enqueue(int x)
{
newnode=(struct node*)malloc(sizeof(struct node));
newnode->data=x;
if(rear==NULL)
{
rear=front=newnode;
rear->next=front;
}
else
{
rear->next=newnode;
rear=newnode;
rear->next=front;
}
}
void dequeue()
{
temp=front;
if((rear==NULL)&&(front==NULL))
printf("Queue is empty\n");
else if(front==rear)
{

17
VCE-R22 ADS LAB
front=rear=NULL;
printf("The deleted element is %d\n",temp->data);
free(temp);
}
else
{
front=front->next;
rear->next=front;
printf("The deleted element is %d\n",temp->data);
free(temp);
}
}
void first()
{
if((rear==NULL)&&(front==NULL))
printf("Queue is empty\n");
else
printf("The front element is %d\n",front->data);
}
void last()
{
if((rear==NULL)&&(front==NULL))
printf("Queue is empty\n");
else
printf("The last element is %d\n",rear->data);
}

18
VCE-R22 ADS LAB
void display()
{
temp=front;
if((rear==NULL)&&(front==NULL))
printf("Queue is empty\n");
else
{
printf("The elements are ");
do
{
printf("%3d",temp->data);
temp=temp->next;
}while(temp!=front);
printf("\n");
}
}
Output:
The elements are 34 10 23
The deleted element is 34
The front element is 10
The last element is 23

19
VCE-R22 ADS LAB
1. Discuss the advantages and disadvantages of using linked list for
the implementation of a circular queue
2. Explain the significance of front and rear pointers in circular
queue
3. Propose a real-world scenario where circular queue can be
Post-Lab implemented.
Questions 4. What is the time and space complexity of algorithm?
5. How does the circular nature of queue effect the enqueue and
dequeue operations?

20
VCE-R22 ADS LAB
Write a C program to implement deque using
Week-3
linked list

1. What is a deque?
Pre-Lab 2. Differentiate between queue, stack and deque.
3. List the basic operations that should be supported by a deque.
Questions
4. How can a deque be implemented using linked lists?

#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *prev,*next;
}*front=NULL,*rear=NULL,*newnode,*p,*q;
int size=0;
void create();
void display();
void InsertFront(int);
void InsertRear(int);
void DeleteFront();
void DeleteRear();
void getFront();
void getRear();
void qsize();
void erase();
void main()
{

21
VCE-R22 ADS LAB
create();
display();
InsertFront(23);
InsertRear(34);
display();
DeleteFront();
DeleteRear();
display();
getRear();
getFront();
qsize();
erase();
display();
}
void create()
{
int n,i;
printf("Enter the no of nodes\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
newnode=(struct node *) malloc(sizeof(struct node));
printf("Enter the data\n");
scanf("%d",&newnode->data);
newnode->next=NULL;
newnode->prev=NULL;

22
VCE-R22 ADS LAB
if(front==NULL)
front=rear=newnode;
else
{
rear->next=newnode;
newnode->prev=rear;
rear=newnode;
}
size++;
}
}
void display()
{
q=front;p=rear;
printf("The elements are ");
while(q)
{
printf("%3d",q->data);
q=q->next;
}
printf("\nThe elements in reverse order are ");
while(p)
{
printf("%3d",p->data);
p=p->prev;
}

23
VCE-R22 ADS LAB
printf("\n");
}
void InsertFront(int x)
{
newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=x;
newnode->next=NULL; newnode->prev=NULL;
if (front == NULL)
rear = front = newnode;
else
{
newnode->next = front;
front->prev = newnode;
front = newnode;
}
size++;
}
void InsertRear(int x)
{
newnode=(struct node *)malloc(sizeof(struct node));
newnode->data=x;
newnode->next=NULL; newnode->prev=NULL;
if (front == NULL)
rear = front = newnode;
else
{

24
VCE-R22 ADS LAB
newnode->prev = rear;
rear->next = newnode;
rear = newnode;
}
size++;
}
void DeleteFront()
{
if(front==NULL)
printf("Deque is empty\n");
else
{
p=front;
front=front->next;
if(front==NULL)
rear=NULL;
else
front->prev=NULL;
free(p);
size--;
}
}
void DeleteRear()
{
if(front==NULL)
printf("Deque is empty\n");

25
VCE-R22 ADS LAB
else
{
p=rear;
rear=rear->prev;
if(rear==NULL)
front=NULL;
else
rear->next=NULL;
free(p);
size--;
}
}
void getRear()
{
if (front==NULL)
printf("Queue is empty\n");
else
printf("The rear element is %d \n", rear->data);
}
void getFront()
{
if (front==NULL)
printf("Queue is empty\n");
else
printf("The front element is %d\n ", front->data);
}

26
VCE-R22 ADS LAB
void qsize()
{
printf("The no of nodes in queue are %d\n",size);
}
void erase()
{
rear = NULL;
while (front != NULL)
{
p = front;
front = front->next;
free(p);
}
size = 0;
}
Output:
Enter the no of nodes
2
Enter the data
1
Enter the data
2
The elements are 1 2
The elements in reverse order are 2 1
The elements are 23 1 2 34
The elements in reverse order are 34 2 1 23

27
VCE-R22 ADS LAB
The elements are 1 2
The elements in reverse order are 2 1
The rear element is 2
The front element is 1
The no of nodes in queue are 2
The elements are
The elements in reverse order are

1. Describe how you implemented the deque using a linked list.


Post-Lab 2. What are the types of deque
3. State the limitations associated with the use of a deque
Questions
4. In what scenarios or applications do you think a deque
implemented using a linked list would be particularly useful?
5. How efficient is the deque implementation in terms of its
runtime performance and memory usage?

28
VCE-R22 ADS LAB
Write a C program to implement addition of two
Week-4
polynomials

1. Explain how polynomials are typically represented in algebraic


Pre-Lab expressions.
2. Discuss the possible data structures that can be used to
Questions
represent polynomials in a computer program.
3. Describe the steps involved in adding two polynomials.
4. Are there different algorithms for polynomial addition, and if
so, what are the key differences?

#include<stdio.h>
#include<malloc.h>
struct node
{
int co,expo;
struct node *next;
}*head=NULL,*newnode,*p,*poly1,*poly2;
struct node* create();
void display(struct node*);
struct node* polyadd();
void main()
{
struct node *poly;
printf("Enter the first polynomial\n");
poly1=create();
printf("Enter the second polynomial\n");
poly2=create();
printf("Polynomials:");
if (poly1==NULL)
29
VCE-R22 ADS LAB
printf("No polynomial 1\n");
else
display(poly1);
if (poly2==NULL)
printf("No polynomial 2\n");
else
display(poly2);
printf(“Addition of two polynomials:\n”);
poly=polyadd();
display(poly);
}
struct node* create()
{
head=NULL; int n,i;
printf("Enter the no. of polynomials\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the coefficient and exponent\n”);
scanf("%d%d",&newnode->co,&newnode->expo);
newnode->next=NULL;
if(head==NULL) //when the first node is created
head=p=newnode;
else
p->next=newnode;

30
VCE-R22 ADS LAB
p=newnode;
}
return head;
}
void display(struct node *p)
{
if(p==NULL) // When the linked list is empty
printf("There is no polynomial\n");
else
{
while(p->next!=NULL)
{
printf("%dx^%d + ",p->co,p->expo);
p=p->next;
}
printf("%dx^%d\n",p->co,p->expo);
}
}
struct node* polyadd()
{
struct node *res=NULL,*p1=poly1,*p2=poly2,*temp;
if((p1!=NULL) && (p2==NULL))
return p1;
else if((p1==NULL) && (p2!=NULL))
return p2;
while((p1!=NULL) && (p2!=NULL))

31
VCE-R22 ADS LAB
{
if(res==NULL)
{
res=(struct node*)malloc(sizeof(struct node));
temp=res;
}
else
{
temp->next=(struct node*)malloc(sizeof(struct node));
temp=temp->next;
}
if(p1->expo>p2->expo)
{
temp->co=p1->co;
temp->expo=p1->expo;
p1=p1->next;
}
else if(p1->expo<p2->expo)
{
temp->co=p2->co;
temp->expo=p2->expo;
p2=p2->next;
}
else if (p1->expo==p2->expo)
{
temp->co=p1->co+p2->co;

32
VCE-R22 ADS LAB
temp->expo=p1->expo;
p1=p1->next;
p2=p2->next;
}
}
while(p1!=NULL)
{
temp->next=(struct node*)malloc(sizeof(struct node));
temp=temp->next;
temp->co=p1->co;
temp->expo=p1->expo;
p1=p1->next;
}
while(p2!=NULL)
{
temp->next=(struct node*)malloc(sizeof(struct node));
temp=temp->next;
temp->co=p2->co;
temp->expo=p2->expo;
p2=p2->next;
}
temp->next=NULL;
return res;
}
Output:
Enter the first polynomial

33
VCE-R22 ADS LAB
Enter the no. of polynomials
3
Enter the coefficient and exponent
32
Enter the coefficient and exponent
21
Enter the coefficient and exponent
50
Enter the second polynomial
Enter the no. of polynomials
2
Enter the coefficient and exponent
22
Enter the coefficient and exponent
51
Polynomials:3x^2 + 2x^1 + 5x^0
2x^2 + 5x^1
Addition of two polynomials:
5x^2 + 7x^1 + 5x^0
1. What data structures were used to represent individual
polynomials?
2. How are like terms identified, and what steps are taken to
simplify the result?
3. How did you handle scenarios where the two polynomials being
Post-Lab added have different degrees?
Questions 4. Propose a real-world scenario where addition of polynomials is
relevant.

34
VCE-R22 ADS LAB
Write a C program to implement multiplication of
Week-5
two polynomials

1. What are coefficients and degrees of a polynomial?


Pre-Lab 2. Can polynomials have missing terms or negative exponents?
3. Explain the basic steps involved in multiplying two polynomials.
Questions
4. What are the advantages and disadvantages of using arrays,
linked lists, or other data structures for polynomial
representation?

#include<stdio.h>
#include<malloc.h>
struct node
{
int co,expo;
struct node *next;
}*head=NULL,*newnode,*p,*poly1,*poly2;
struct node* create();
void display(struct node*);
struct node* polymul();
void main()
{
struct node *poly;
printf("Enter the first polynomial\n");
poly1=create();
printf("Enter the second polynomial\n");
poly2=create();
printf("Polynomials:");
if (poly1==NULL)
35
VCE-R22 ADS LAB
printf("No polynomial 1\n");
else
display(poly1);
if (poly2==NULL)
printf("No polynomial 2\n");
else
display(poly2);
printf(“Multiplication of two polynomials:\n”);
poly=polymul();
display(poly);
}
struct node* create()
{
head=NULL; int n,i;
printf("Enter the no. of polynomials\n");
scanf("%d",&n);
for(i=1;i<=n;i++)
{
newnode=(struct node*)malloc(sizeof(struct node));
printf("Enter the coefficient and exponent\n”);
scanf("%d%d",&newnode->co,&newnode->expo);
newnode->next=NULL;
if(head==NULL) //when the first node is created
head=p=newnode;
else
p->next=newnode;

36
VCE-R22 ADS LAB
p=newnode;
}
return head;
}
void display(struct node *p)
{
if(p==NULL) // When the linked list is empty
printf("There is no polynomial\n");
else
{
while(p->next!=NULL)
{
printf("%dx^%d + ",p->co,p->expo);
p=p->next;
}
printf("%dx^%d\n",p->co,p->expo);
}
}
struct node* polymul()
{
struct node *res=NULL, *p1=poly1,*pt=poly2, *p2=poly2,*temp, *t;
int flag=0;
while(p1!=NULL)
{
while(p2!=NULL)
{

37
VCE-R22 ADS LAB
if(res==NULL)
{
res=(struct node*) malloc(sizeof(struct node));
temp=t=res;
}
else
{
while(t)
{
if(t->expo==p1->expo+p2->expo)
{
t->co+=p1->co*p2->co;
flag=1;break;
}
else
t=t->next;
}
if(flag==1)
{
p2=p2->next;
t=res;
flag=0;continue;
}
temp->next = (struct node *) malloc(sizeof(struct node));
temp=temp->next;
}

38
VCE-R22 ADS LAB
temp->co=p1->co*p2->co;
temp->expo=p1->expo+p2->expo;
temp->next=NULL;
p2=p2->next; t=res;
}
p2=pt;
p1=p1->next;
}
return res;
}

Output:
Enter the first polynomial
Enter the no. of polynomials
2
Enter the coefficient and exponent
32
Enter the coefficient and exponent
41
Enter the second polynomial
Enter the no. of polynomials
2
Enter the coefficient and exponent
21
Enter the coefficient and exponent
30

39
VCE-R22 ADS LAB
Polynomials:3x^2 + 4x^1
2x^1 + 3x^0
Multiplication of two polynomials:
6x^3 + 17x^2 + 12x^1
1. What is the significance of exponents in multiplication of
polynomials? How does it differ from addition of polynomials?
2. Explain a real-world scenario where multiplication of
polynomials is relevant.
3. What challenges might arise during multiplication of
Post-Lab polynomials, how can they be addressed?
Questions 4. Were there any areas where optimization opportunities were
identified?

40
VCE-R22 ADS LAB
Write a C program to implement Heap Sort
Week-6

1. Explain the concept of a heap data structure.


Pre-Lab 2. Differentiate between a min-heap and a max-heap.
3. What is the heapify operation, and how is it performed on a
Questions
binary heap?
4. Explain the difference between heapifying an entire array and a
single subtree.
5. How does Heap Sort use the heap data structure to achieve
sorting?
6. Describe how a binary heap can be represented in an array.

#include <stdio.h>
int size = 0;
void heapSort(int array[], int size) ;
void heapify(int array[], int size, int i);
void create(int array[]);
void printArray(int array[], int size);
int main()
{
int array[10];
create(array);
printArray(array, size);
heapSort(array,size);
printArray(array, size);
}
void create(int array[])
{
int n,i,newNum;
printf(“Enter the number of elements\n”);

41
VCE-R22 ADS LAB
scanf(“%d”,&n);
for(size=0;size<n;i++)
{
printf(“Enter the element\n”);
scanf(“%d”,&newNum);
if (size == 0)
array[0] = newNum;
else
{
array[size] = newNum;
for (int i = size / 2 - 1; i>= 0; i--)
{
heapify(array, size, i);
}
}
}
}
void heapSort(int array[], int size)
{
int i,temp;
for (i = size / 2 - 1; i>= 0; i--)
heapify(array, size, i);
for (i=size-1; i>=0; i--)
{
temp = array[0];
array[0]= array[i];

42
VCE-R22 ADS LAB
array[i] = temp;
heapify(array, i, 0);
}
}
void heapify(int array[], int size, int i)
{
int temp;
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && array[l] > array[largest])
largest = l;
if (r < size && array[r] > array[largest])
largest = r;
if (largest != i)
{
temp = array[i];
array[i]= array[largest];
array[largest] = temp;
heapify(array, size, largest);
}
}
void printArray(int array[], int size)
{
for (int i = 0; i< size; ++i)
printf("%d ", array[i]);

43
VCE-R22 ADS LAB
printf("\n");
}
Output:
Enter the number of elements
3
Enter the element
3
Enter the element
76
Enter the element
12
76 3 12
3 12 76
1. Discuss the role of the heapify operation in the sorting process.
2. How is the initial heap constructed before the sorting phase?
3. Discuss whether Heap Sort is a stable sorting algorithm
4. Compare the efficiency and performance characteristics of
Post-Lab
Heap Sort with other sorting algorithms like Quick Sort and
Questions Merge Sort.
5. In what real-world scenarios or applications might Heap Sort be
a suitable choice for sorting data?

44
VCE-R22 ADS LAB
Write a C program to implement Binary search
Week-7
trees – operations: insertion, deletion, searching
and traversal

1. What is a Binary Search Tree (BST), and how does it differ from
Pre-Lab other binary tree structures?
2. Explain the key property of a BST that makes searching efficient.
Questions
3. Describe the structure of a node in a Binary Search Tree.
4. Outline the steps involved in inserting a new key into a Binary
Search Tree.
5. What are the different cases that need to be considered during
deletion?
6. How does the BST property assist in optimizing the search
process?
7. Define the concepts of in-order, pre-order, and post-order
traversals in a Binary Search Tree.

#include<stdio.h>
#include<malloc.h>
struct node
{
int data;
struct node *right_child;
struct node *left_child;
}*root=NULL,*temp;
struct node* insert(struct node*,int);
struct node* search(struct node*,int);
void inorder(struct node*);
void preorder(struct node*);
void postorder(struct node*);
struct node* delete(struct node*,int);
struct node* find_min(struct node*);

45
VCE-R22 ADS LAB
void main()
{
root=insert(root,1);
insert(root,4);
insert(root,5);
insert(root,3);
root=delete(root,4);
if ((search(root,5))==NULL)
printf("Element not found\n");
else
printf("Element found\n");
printf("Inorder traversal is:\n");
inorder(root);
printf("\nPreorder traversal is:\n");
preorder(root);
printf("\nPostorder traversal is:\n");
postorder(root);
}
struct node* insert(struct node* root, int x)
{
if(root==NULL)
{
temp=(struct node*)malloc(sizeof(struct node));
temp->data=x;
temp->left_child=temp->right_child=NULL;
root=temp;

46
VCE-R22 ADS LAB
}
else if(x > root->data)
root->right_child=insert(root->right_child,x);
else
root->left_child=insert(root->left_child,x);
return root;
}
struct node* search(struct node* root, int x)
{
if(root==NULL || root->data==x)
return root;
else if(x > root->data)
return search(root->right_child,x);
else
return search(root->left_child,x);
}
void inorder(struct node *root)
{
if(root!=NULL)
{
inorder(root->left_child);
printf("%d ", root->data);
inorder(root->right_child);
}
}
void preorder(struct node *root)

47
VCE-R22 ADS LAB
{
if(root!=NULL)
{
printf("%d ",root->data);
preorder(root->left_child);
preorder(root->right_child);
}
}
void postorder(struct node *root)
{
if(root!=NULL)
{
postorder(root->left_child);
postorder(root->right_child);
printf("%d ",root->data);
}
}
struct node* delete(struct node* root, int x)
{
if(root==NULL)
return root;
if (x>root->data)
root->right_child = delete(root->right_child, x);
else if(x<root->data)
root->left_child = delete(root->left_child, x);
else

48
VCE-R22 ADS LAB
{
if(root->left_child==NULL && root->right_child==NULL)
{
free(root);
return NULL;
}
else if(root->left_child==NULL || root->right_child== NULL)
{
struct node *temp;
if(root->left_child==NULL)
temp = root->right_child;
else
temp = root->left_child;
free(root);
return temp;
}
else
{
struct node *temp = find_min(root->right_child);
root->data = temp->data;
root->right_child = delete(root->right_child, temp->data);
}
}
return root;
}
struct node* find_min(struct node* root)

49
VCE-R22 ADS LAB
{
if(root == NULL)
return NULL;
else if(root->left_child != NULL)
return find_min(root->left_child);
return root;
}

Output:
Element found
Inorder traversal is:
135
Preorder traversal is:
153
Postorder traversal is:
351

1. How the insertion operation was implemented in your Binary


Search Tree program?
2. How did your program handle scenarios like deleting a node
with one or two children?
3. Discuss the algorithm used for searching a key in your Binary
Post-Lab Search Tree implementation.
Questions 4. In what practical situations or applications might Binary Search
Trees be used for efficient searching and retrieval?

50
VCE-R22 ADS LAB
Write a C program to implement Breadth First
Week-8
Search (BFS).

1. What is Breadth-First Search (BFS), and how does it differ from


Pre-Lab Depth-First Search (DFS)?
2. Explain the basic principle behind BFS in traversing a graph or
Questions
tree.
3. What data structures are commonly used to keep track of
visited nodes during BFS?
4. Discuss different ways to represent a graph in programming.

#include<stdio.h>
#define initial 1
#define waiting 2
#define visited 3
#define MAX 5
int queue[MAX];
int front=-1,rear=-1,n;
int G[MAX][MAX], state[10];
void insert_queue(int);
int delete_queue();
void bf_traversal();
void create_graph();
void bfs(int v);
void main()
{
create_graph();
bf_traversal();
}
void create_graph()

51
VCE-R22 ADS LAB
{
int origin,destin,c,max_edge;
printf("Enter number of vertices : ");
scanf("%d",&n);
max_edge = n*(n-1);
for(c=1;c<=max_edge;c++)
{
printf("Enter edge %d(-1 -1 to quit):",c);
scanf("%d%d",&origin,&destin);
if(origin==-1 &&destin==-1)
break;
else if(origin>=n || destin>=n || origin<0 || destin<0)
{
printf("Invalid edge!\n");
c--;
}
else
G[origin][destin]=1;
}
}
void bf_traversal()
{
int v;
for(v=0; v<n; v++)
state[v] = initial;
printf("Enter Start Vertex for BFS: \n");

52
VCE-R22 ADS LAB
scanf("%d", &v);
bfs(v);
}
void bfs(int v)
{
int i;
insert_queue(v);
state[v]=waiting;
while(rear!=-1 && front!=rear+1)
{
v = delete_queue();
printf("%d ",v);
state[v] = visited;
for(i=0; i<n; i++)
{
if(G[v][i] == 1 && state[i] == initial)
{
insert_queue(i);
state[i] = waiting;
}
}
}
}
void insert_queue(int x)
{
if(front==-1)

53
VCE-R22 ADS LAB
front++;
queue[++rear]=x;
}
int delete_queue()
{
return(queue[front++]);
}
Output:
Enter number of vertices : 3
Enter edge 1(-1 -1 to quit):0 1
Enter edge 2(-1 -1 to quit):1 2
Enter edge 3(-1 -1 to quit):0 2
Enter edge 4(-1 -1 to quit):2 1
Enter edge 5(-1 -1 to quit):-1 -1
Enter Start Vertex for BFS:
0
012

1. What data structures did you use to represent the graph and to
manage the BFS traversal?
2. Discuss how you represented the graph in your BFS
implementation.
3. Explain the testing strategy you employed to validate the
Post-Lab correctness and efficiency of your BFS implementation.
Questions 4. Can you provide examples of real-world problems where BFS is
commonly employed?

54
VCE-R22 ADS LAB
Write a C program to implement Depth First Search
Week-9
(DFS).

1. Explain the basic principle behind DFS in traversing a graph or


Pre-Lab tree.
2. How is a stack used in DFS?
Questions
3. Outline the high-level steps of the DFS algorithm.
4. Explain the basic syntax for stack operations in C.

#include<stdio.h>
#define MAX 10
int n;
int visited[MAX];
int adj[MAX][MAX];
void create_graph();
void dfs(int);
void main()
{
int v;
create_graph();
printf("Enter the starting vertex\n");
scanf("%d",&v);
dfs(v);
}
void create_graph()
{
int origin,destin,c,max_edge;
printf("Enter number of vertices : ");
scanf("%d",&n);

55
VCE-R22 ADS LAB
max_edge = n*(n-1);
for(c=1;c<=max_edge;c++)
{
printf("Enter edge %d(-1 -1 to quit):",c);
scanf("%d%d",&origin,&destin);
if(origin==-1 &&destin==-1)
break;
else if(origin>=n || destin>=n || origin<0 || destin<0)
{
printf("Invalid edge!\n");
c--;
}
else
adj[origin][destin]=1;
}
}
void dfs(int i)
{
int j;
printf("%d ",i);
visited[i]=1;
for(j=0;j<n;j++)
{
if(!visited[j]&&adj[i][j]==1)
dfs(j);
}

56
VCE-R22 ADS LAB
}

Output:
Enter number of vertices : 3
Enter edge 1(-1 -1 to quit):0 1
Enter edge 2(-1 -1 to quit):1 2
Enter edge 3(-1 -1 to quit):0 2
Enter edge 4(-1 -1 to quit):2 1
Enter edge 5(-1 -1 to quit):-1 -1
Enter the starting vertex
0
012

1. Describe how you implemented the Depth-First Search


algorithm in your program.
2. Discuss how you represented the graph in your DFS
implementation.
Post-Lab 3. Were there any specific considerations in choosing an
Questions appropriate representation?
4. In what scenarios might DFS be preferred over BFS, and why?

57
VCE-R22 ADS LAB
Write a C program to implement AVL Tree,
Week-10
Operations – Insertion, Deletion and Searching

1. What is an AVL Tree, and how does it differ from a regular


Pre-Lab Binary Search Tree (BST)?
2. Explain the concept of balancing in AVL Trees and its
Questions
significance.
3. How is the balancing factor calculated for each node in the
tree?
4. Outline the key operations performed on AVL Trees, including
insertion, deletion, and searching.
5. How do these operations differ from their counterparts in a
regular BST?
6. When and how are left and right rotations applied during AVL
Tree operations?

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

struct Node {
int key;
struct Node *left, *right;
int height;
};

int max(int a, int b) {


return (a > b) ? a : b;
}

int height(struct Node *N) {


if (N == NULL)

58
VCE-R22 ADS LAB
return 0;
return N->height;
}

struct Node *newNode(int key) {


struct Node *node = (struct Node *)malloc(sizeof(struct Node));
node->key = key;
node->left = node->right = NULL;
node->height = 1;
return node;
}

struct Node *rightRotate(struct Node *y) {


struct Node *x = y->left;
struct Node *T2 = x->right;

x->right = y;
y->left = T2;

y->height = max(height(y->left), height(y->right)) + 1;


x->height = max(height(x->left), height(x->right)) + 1;

return x;
}

struct Node *leftRotate(struct Node *x) {

59
VCE-R22 ADS LAB
struct Node *y = x->right;
struct Node *T2 = y->left;

y->left = x;
x->right = T2;

x->height = max(height(x->left), height(x->right)) + 1;


y->height = max(height(y->left), height(y->right)) + 1;

return y;
}

int getBalance(struct Node *N) {


if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}

struct Node *insert(struct Node *node, int key) {


if (node == NULL)
return newNode(key);

if (key < node->key)


node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);

60
VCE-R22 ADS LAB
else
return node;

node->height = 1 + max(height(node->left), height(node->right));

int balance = getBalance(node);

if (balance > 1 && key < node->left->key)


return rightRotate(node);

if (balance < -1 && key > node->right->key)


return leftRotate(node);

if (balance > 1 && key > node->left->key) {


node->left = leftRotate(node->left);
return rightRotate(node);
}

if (balance < -1 && key < node->right->key) {


node->right = rightRotate(node->right);
return leftRotate(node);
}

return node;
}

61
VCE-R22 ADS LAB
struct Node *minValueNode(struct Node *node) {
struct Node *current = node;
while (current->left != NULL)
current = current->left;
return current;
}

struct Node *deleteNode(struct Node *root, int key) {


if (root == NULL)
return root;

if (key < root->key)


root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else {
if ((root->left == NULL) || (root->right == NULL)) {
struct Node *temp = root->left ? root->left : root->right;
if (temp == NULL) {
temp = root;
root = NULL;
} else
*root = *temp;
free(temp);
} else {
struct Node *temp = minValueNode(root->right);

62
VCE-R22 ADS LAB
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
}

if (root == NULL)
return root;

root->height = 1 + max(height(root->left), height(root->right));

int balance = getBalance(root);

if (balance > 1 &&getBalance(root->left) >= 0)


return rightRotate(root);

if (balance > 1 &&getBalance(root->left) < 0) {


root->left = leftRotate(root->left);
return rightRotate(root);
}

if (balance < -1 &&getBalance(root->right) <= 0)


return leftRotate(root);

if (balance < -1 &&getBalance(root->right) > 0) {


root->right = rightRotate(root->right);
return leftRotate(root);

63
VCE-R22 ADS LAB
}

return root;
}

struct Node *search(struct Node *root, int key) {


if (root == NULL || root->key == key)
return root;

if (key < root->key)


return search(root->left, key);

return search(root->right, key);


}

void preOrder(struct Node *root) {


if (root != NULL) {
printf("%d ", root->key);
preOrder(root->left);
preOrder(root->right);
}
}

int main() {
struct Node *root = NULL;

64
VCE-R22 ADS LAB
root = insert(root, 10);
root = insert(root, 20);
root = insert(root, 30);
root = insert(root, 40);
root = insert(root, 50);
root = insert(root, 25);

printf("Preorder traversal of AVL tree: ");


preOrder(root);
printf("\n");

int keyToDelete = 30;


root = deleteNode(root, keyToDelete);
printf("Key %d deleted from AVL tree\n", keyToDelete);

printf("Preorder traversal after deletion: ");


preOrder(root);
printf("\n");

int keyToSearch = 40;


struct Node *searchResult = search(root, keyToSearch);
if (searchResult != NULL)
printf("Key %d found in AVL tree\n", keyToSearch);
else
printf("Key %d not found in AVL tree\n", keyToSearch);

65
VCE-R22 ADS LAB
return 0;
}
Output:
Preorder traversal of AVL tree: 30 20 10 25 40 50
Key 30 deleted from AVL tree
Preorder traversal after deletion: 40 20 10 25 50
Key 40 found in AVL tree

1. Describe how you implemented AVL Trees and the operations


of insertion, deletion, and searching in your program.
2. Were there any challenges in ensuring that the balancing factor
remained within the acceptable range?
3. Discuss the scenarios in which rotations (single and double)
Post-Lab were applied during AVL Tree operations.
Questions 4. Explain the steps taken to implement the deletion operation in
AVL Trees.
5. In what scenarios might AVL Trees be preferred over regular
BSTs?

66
VCE-R22 ADS LAB
Write a C program to implement Dictionaries.
Week-11

1. What is a dictionary data structure, and what are its key


Pre-Lab characteristics?
2. How does a dictionary differ from other data structures, such as
Questions
arrays or linked lists?
3. How are keys and values associated in a dictionary?
4. What are the different ways to implement dictionaries?

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

struct Node {
int key;
int value;
struct Node* next;
}* head = NULL,*temp;

void insert(int key, int value)


{
temp = head;
while (temp != NULL)
{
if (temp->key == key)
{
temp->value = value;
return;
}

67
VCE-R22 ADS LAB
temp = temp->next;
}

// Key not found, create a new node


struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->key = key;
newNode->value = value;
newNode->next = NULL;
if (head == NULL)
{
head = newNode;
} else {
temp = head;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}

// Deletion Procedure
void deleteKey(int key)
{
temp = head;
struct Node* prev = NULL;

68
VCE-R22 ADS LAB
while (temp != NULL)
{
if (temp->key == key)
{

if (prev == NULL)
head = temp->next;
else
prev->next = temp->next;

free(temp);
return;
}
prev = temp;
temp = temp->next;
}}

// Search Procedure
int search(int key) {
temp = head;

while (temp != NULL) {


if (temp->key == key) {
return temp->value;
}

69
VCE-R22 ADS LAB
temp = temp->next;
}

// Key not found


return -1;
}

// Display Procedure
void display() {
temp = head;

while (temp != NULL) {


printf("Key: %d, Value: %d\n", temp->key, temp->value);
temp = temp->next;
}
}

int main() {
// Test the procedures
insert(1, 10);
insert(2, 20);
insert(3, 30);
printf("Initial List:\n");
display();
int searchKey = 2;
int searchResult = search(searchKey);

70
VCE-R22 ADS LAB
printf("\nSearch result for key %d: %d\n", searchKey, searchResult);
deleteKey(2);
printf("\nList after deleting key %d:\n", deleteKey);
display();
return 0;
}
Output:
Initial List:
Key: 1, Value: 10
Key: 2, Value: 20
Key: 3, Value: 30

Search result for key 2: 20


List after deleting key 4198971:
Key: 1, Value: 10
Key: 3, Value: 30

1. What choices did you make regarding data structures and


algorithms for dictionary operations?
2. How were keys and values stored, and what data structures
were used?
3. Discuss any potential memory-related issues and how they
Post-Lab were addressed.
Questions 4. Can you think of any extensions or modifications to the basic
dictionary implementation that could enhance functionality or
performance?

71
VCE-R22 ADS LAB
Write a C program to implementation of Hash
Week-12
Table with linear probing.

1. What is a hash table, and how does it work in storing and


retrieving data efficiently?
2. What is a hash function, and how is it used in hash table
implementations?
Pre-Lab
3. Describe the characteristics of a good hash function.
Questions 4. What is a collision in hash table?
5. Discuss different strategies for handling collisions in hash table
implementations.
6. Define linear probing as a collision resolution technique.

#include<stdio.h>
#define SIZE 10
int hashTable[SIZE];
void initHashTable()
{
for (int i = 0; i< SIZE; i++)
{
hashTable[i] = -1;
}
}

int hashFunction(int key) {


return (key % SIZE);}

void insert(int key)


{
int index = hashFunction(key);

72
VCE-R22 ADS LAB
while (hashTable[index] != -1) // Linear probing: move to the next slot
{
index = (index + 1) % SIZE;
}
hashTable[index] = key; // Insert the key
printf("Inserted %d at index %d\n", key, index);
}

int search(int key)


{
int index = hashFunction(key);
while (hashTable[index] != -1)
{
if (hashTable[index] == key) // Check if the key matches
{
return index; // Key found, return the index
}
index = (index + 1) % SIZE; // Linear probing: move to the next slot
}
return -1; // Key not found
}

void delete(int key)


{
int index = search(key);
if (index != -1)

73
VCE-R22 ADS LAB
{
hashTable[index] = -1; // Mark the slot as empty (-1 indicates an empty slot)
printf("Deleted key %d at index %d\n", key, index);
}
else
{
printf("Key %d not found in the hash table\n", key);
}
}

void display()
{
printf("Hash Table:\n");
for (int i = 0; i< SIZE; i++)
{
printf("[%d] -> ", i);
if (hashTable[i] != -1)
{
printf("%d", hashTable[i]);
}
else
{ printf("Empty");
}
printf("\n");
}
}

74
VCE-R22 ADS LAB
void main()
{
int x;
initHashTable();
insert(20);
insert(30);
insert(15);
x=search(15);
if(x==-1)
printf("Element not found\n");
else
printf("Element found at index %d\n",x);
printf("The elements are\n");
display();
delete(30);
printf("After deleting, The elements are\n");
display();
}
Output:
Inserted 20 at index 0
Inserted 30 at index 1
Inserted 15 at index 5
Element found at index 5
The elements are
Hash Table:

75
VCE-R22 ADS LAB
[0] -> 20
[1] -> 30
[2] -> Empty
[3] -> Empty
[4] -> Empty
[5] -> 15
[6] -> Empty
[7] -> Empty
[8] -> Empty
[9] -> Empty
Deleted key 30 at index 1
After deleting, The elements are
Hash Table:
[0] -> 20
[1] -> Empty
[2] -> Empty
[3] -> Empty
[4] -> Empty
[5] -> 15
[6] -> Empty
[7] -> Empty
[8] -> Empty
[9] -> Empty

76
VCE-R22 ADS LAB
1. Describe the hash function used in your hash table
implementation.
2. Discuss the strategy you employed for handling collisions with
linear probing.
3. Compare linear probing with other collision resolution
Post-Lab techniques, such as chaining, in terms of their advantages,
Questions disadvantages, and use cases.
4. In what scenarios might linear probing be preferred over other
techniques, and vice versa?

77
VCE-R22 ADS LAB
Write a C program to implement Brute-Force
Week-13
Pattern Matching , Boyer- Moore Algorithm.

1. What is pattern matching, and why is it important in computer


Pre-Lab science?
2. Explain the significance of efficient pattern matching
Questions
algorithms.
3. Describe the Brute-Force pattern matching algorithm
4. What are the key features that make Boyer-Moore more
efficient than Brute-Force in certain cases?
5. Compare the time complexity of Brute-Force and Boyer-Moore
algorithms.

#include<stdio.h>
#include<string.h>
void BMSearch( char *, char *);
void badCharHeuristic( char *, int, int[]);
void brute_force(char*,char*);
int max(int,int);
void main()
{
char *t="Welcome to ADS lab";
char *p="ADS";
BMSearch(t,p);
brute_force(t,p);
}
void brute_force(char t[20],char p[10])
{
int flag=0,n,m,j,i;
n=strlen(t);
m=strlen(p);
78
VCE-R22 ADS LAB
for(i=0;i<n;i++)
{
j=0;
while(j<m && t[i+j]==p[j])
j++;
if(j==m)
{
printf("Using brute force, pattern found at %d\n",i+1);
flag=1;
}
}
if(i==n && flag==0)
printf("pattern not found\n");
}

void badCharHeuristic( char *str, int m, int badchar[256])


{
int i;
// Initialize all occurrences as -1
for (i = 0; i< 256; i++)
badchar[i] = -1;
// Fill the index of last occurrence of a character
for (i = 0; i< m; i++)
badchar[(int) str[i]] = i;
}
void BMSearch( char *txt, char *pat)

79
VCE-R22 ADS LAB
{
int m = strlen(pat), n = strlen(txt), badchar[256],i=0, flag=0,j;
badCharHeuristic(pat, m, badchar);
while(i<= (n - m))
{
j = m-1;
while(j >= 0 && pat[j] == txt[i+j])
j--;
if (j < 0)
{
printf("Using Boyer Moore, Pattern found at location = %d\n",
i+1);
i += (i+m< n)? m-badchar[txt[i+m]] : 1;
flag=1;
}
else
i += max(1, j - badchar[txt[i+j]]);

if(i>n-m&&flag==0)
printf("Pattern not found in text");
}
}
int max(int a,int b)
{
return (a>b)?a:b;
}
Output:
80
VCE-R22 ADS LAB
Using Boyer Moore, Pattern found at location = 12
Using brute force, pattern found at 12

1. Explain the steps taken by the Brute-Force algorithm during


pattern matching.
2. How does it handle multiple occurrences of the pattern in the
text?
3. Discuss the key features and steps involved in the Boyer-Moore
Post-Lab algorithm during pattern matching. How does it utilize
Questions preprocessing to improve efficiency?
4. Can you provide examples of real-world problems where
efficient pattern matching is crucial?
5. In what scenarios might Boyer-Moore be preferred over other
algorithms, and vice versa?

81
VCE-R22 ADS LAB
Write a C program to implement Knuth-Morris-
Week-14
Pratt Algorithm.

1. What are the key features that distinguish KMP from other
Pre-Lab pattern matching algorithms?
2. What is the role of the prefix function in the KMP algorithm?
Questions
3. How does the prefix function contribute to the efficiency of the
algorithm?
4. Compare the time complexity of the KMP algorithm with other
pattern matching algorithms, such as Brute-Force or Boyer-
Moore.

#include<stdio.h>
#include<string.h>
void computeLPSArray(char[], int, int[]);
void KMPSearch(char*, char*);
void main()
{
char *t="Welcome to ADS lab";
char *p="ADS";
KMPSearch(t,p);
}
void computeLPSArray(char* pat, int M, int lps[])
{
int len = 0;
int i = 1;
lps[0] = 0;
while (i< M)
{

82
VCE-R22 ADS LAB
if (pat[i] == pat[len])
{
len++;
lps[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
if (len != 0)
len = lps[len - 1];
else // len = 0
{
lps[i] = len;
i++;
}
}
}
}
void KMPSearch(char* txt, char* pat)
{
int M = strlen(pat);
int N = strlen(txt);
int lps[M];
computeLPSArray(pat, M, lps);
int i = 0; // index for txt[]
int j = 0; // index for pat[]

83
VCE-R22 ADS LAB
while ((N - i) >= (M - j))
{
if (pat[j] == txt[i])
{
j++;
i++;
}

if (j == M)
{
printf("Found pattern at index %d ", i - j);
j = lps[j - 1];
}
else if (i< N && pat[j] != txt[i])
{
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
}
Output:
Found pattern at index 11

84
VCE-R22 ADS LAB
1. Describe how you implemented the Knuth-Morris-Pratt
algorithm in your program.
2. Explain the role and steps involved in the prefix function during
pattern matching in the KMP algorithm
3. Were there specific scenarios where the KMP algorithm
Post-Lab demonstrated superior efficiency?
Questions 4. Were there any areas where optimization opportunities were
identified?
5. In what scenarios might KMP be preferred over other
algorithms, and vice versa?

85
VCE-R22 ADS LAB

You might also like