DS Mannual Updated Shanti

Download as pdf or txt
Download as pdf or txt
You are on page 1of 82

[TYPE THE COMPANY NAME]

[Type the document title]

[Type the document subtitle]

ADMIN
[Pick the date]

[Type the abstract of the document here. The abstract is typically a short summary
of the contents of the document. Type the abstract of the document here. The
abstract is typically a short summary of the contents of the document.]
St.Mary’s Group of Institutions, Hyderabad
Near Ramoji Film City, Behind Mount Opera, Deshmukhi
Village, Pochampally Mandal, Yadadri Bhuvanagiri District

DEPARTMENT OF ARTIFICIAL INTELLIGENCE & MACHINE LEARNING

DATA STRUCTURES
LAB MANUAL

Regulation : R22/JNTUH Academic Year : 2023-2024


II B. TECH I SEMESTER

DEPARTMENT OF ARTIFICIAL INTELLIGENCE & MACHINE LEARNING


VISION AND MISSION OF THE INSTITUTION
VISION
To become self-sustainable institution this is recognized for its
new age engineering through innovative teachingand learning
culture, inculcating research and entrepreneurial ecosystem, and
sustainable social impact in the community.
MISSION
 To offer undergraduate and post-graduate programs that is
supported through industry relevant curriculum and innovative
teaching and learning processes that would help students
succeed in their professional careers.
 To provide necessary support structures for students, this will
contribute to their personal and professionalgrowth and enable
them to become leaders in their respective fields.
 To provide faculty and students with an ecosystem that fosters
research and development through strategic partnerships with
government organizations and collaboration with industries.
 To contribute to the development of the region by using our
technological expertise to work with nearbycommunities and
support them in their social and economic growth.

3
VISION AND MISSION OF AIML DEPARTMENT
VISION
To be recognized as a department of excellence by stimulating a
learning environment in which students and faculty will thrive
and grow to achieve their professional, institutional and societal
goals.
MISSION
 To provide high quality technical education to students that will
enable life-long learning and buildexpertise in advanced
technologies in Computer Science and Engineering.
 To promote research and development by providing
opportunities to solve complex engineeringproblems in
collaboration with industry and government agencies.
 To encourage professional development of students that will
inculcate ethical values and leadership skills while working
with the community to address societal issues.

4
PROGRAM EDUCATIONAL OBJECTIVES (PEOS):
A graduate of the Computer Science and Engineering Program
should:
Program Educational Objective1: (PEO1)
The Graduates will provide solutions to difficult and challenging
PEO1 issues in their professionby applying computer science and
engineering theory and principles.
Program Educational Objective2 :( PEO2)
The Graduates have successful careers in computer science and
PEO2 engineering fields or will beable to successfully pursue advanced
degrees.
Program Educational Objective3: (PEO3)
The Graduates will communicate effectively, work collaboratively
PEO3 and exhibit high levels ofProfessionalism, moral and ethical
responsibility.
Program Educational Objective4 :( PEO4)
The Graduates will develop the ability to understand and analyze
PEO4 Engineering issues in a broader perspective with ethical
responsibility towards sustainable development.

PROGRAM OUTCOMES (POS):

Engineering knowledge: Apply the knowledge of mathematics,


science, engineering Fundamentals and an engineering
PO1 specialization to the solution of complex engineering problems.

5
Problem analysis: Identify, formulate, review research literature,
PO2 and analyze complete Engineering problems reaching
substantiated conclusions using first principles of mathematics,
natural sciences, and engineering sciences.
Design/development of solutions: Design solutions for complex
engineering problems and design system components or
PO3 processes that meet the specified needs with appropriate
Consideration for the public health and safety, and the cultural,
societal, and environmental considerations.
Conduct investigations of complex problems: Use research-based
PO4 knowledge and research methods including design of experiments,
analysis and interpretation of data, and synthesis ofthe
information to provide valid conclusions.

Modern tool usage: Create, select, and apply appropriate


PO5 techniques, resources, and modern engineering and IT tools
including prediction and modeling to complex engineering
activities wtihan understanding of the limitations.
The engineer and society: Apply reasoning informed by the
PO6 contextual knowledge to assess societal, health, safety, legal and
cultural issues and the consequent responsibilities relevant tothe
professional engineering practice.
Environment and sustainability: Understand the impact of the
PO7 professional engineering Solutions in societal and environmental
contexts, and demonstrate the knowledge of, and needfor
sustainable development.
Ethics: Apply ethical principles and commit to professional ethics
PO8 and responsibilities andnorms of the engineering practice.
Individual and team work: Function effectively as an individual,
PO9 and as a member or leaderIn diverse teams, and in multi-
disciplinary settings.

6
Communication: Communicate effectively on complex
engineering activities with the engineering community and with
PO1 society at large, such as, being able to comprehend and write
0 effective reports and design documentation, make effective
presentations, and give and receiveclear instructions.
Project management and finance: Demonstrate knowledge and
PO1 understanding of the Engineering and management principles and
1 apply these to one’s own work, as a member andleader in a team,
to manage projects and in multidisciplinary environments.
Life-long learning: Recognize the need for, and have the
PO1 preparation and ability to engage in independent and life-long
2 learning in the broadest context of technological
change.

PROGRAM SPECIFIC OUTCOMES(PSOS):

Problem Solving Skills – Graduate will be able to apply


computational techniques and
PSO1 software principles to solve complex engineering problems
pertaining to software engineering.
Professional Skills – Graduate will be able to think critically,
PSO2 communicate effectively, andcollaborate in teams through
participation in co and extra-curricular activities.
Successful Career – Graduates will possess a solid foundation in
PSO3 computer science and engineering that will enable them to grow
in their profession and pursue lifelong learningthrough post-
graduation and professional development.

DEPARTMENT OF ARTIFICIAL INTELLIGENCE &


MACHINE LEARNING
PREREQUISITES:
A course on “Programming for Problem Solving” L T P C
7 0 0 3 1.5
COURSE OBJECTIVES:
 It covers various concepts of C programming language
 It introduces searching and sorting algorithms
 It provides an understanding of data structures such as stacks
and queues.
COURSE OUTCOME
 Ability to develop C programs for computing and real-
life applications using basic elements like control
statements, arrays, functions, pointers and strings, and
datastructures like stacks, queues and linked lists.
 Ability to Implement searching and sorting algorithms
List of Experiments:

1. Writea program that uses functions to perform the following


operations on singly linked list:
i) Creation ii) Insertion iii) Deletion iv)Traversal
2. Writea program that uses functions to perform the following
operations on doubly linked list:
i) Creation ii) Insertion iii) Deletion iv)Traversal
3. Writea program that uses functions to perform the following
operations on circular linked list:
i) Creation ii) Insertion iii) Deletion iv) Traversal
4. Write a program that implement stack (its operations) using
i) Arrays ii) Pointers
5. Write a program that implement Queue (its operations) using
i) Arrays ii) Pointers
6. Write a program that implements the following sorting methods

8
to sort a given list of integers in ascending order
i) Quick sort ii) Heap sort iii) Merge sort
7. Write
a program to implement the tree traversal methods(
Recursive and Non Recursive).
8. Write a program to implement
i) Binary Search tree ii) B Trees iii) B+ Trees iv) AVL
trees v) Red - Black trees
9. Write a program to implement the graph traversal methods.
10. Implement a Pattern matching algorithms using Boyer- Moore,
Knuth-Morris-Pratt

9
INDEX
S.No. Name of the Program Page
No.
Week1
Write a program that uses functions to perform the following operations on singly
linked list:
1
i) Creation ii) Insertion iii) Deletion iv)Traversal
Week 2
Write a program that uses functions to perform the following operations on doubly
linked list:
2
i) Creation ii) Insertion
iii) Deletion iv) Traversal
Week 3
Write a program that uses functions to perform the following operations on circular
linked list:
3
i) Creation ii) Insertioniii) Deletion iv)Traversal
Week 4
Write a program that implement stack (its operations) using
4 i) Arrays ii) Pointers
Week 5
Write a program that implement Queue (its operations) using
5 i) Arrays ii) Pointers
Week 6
Write a program that implements the following sorting methods to sort a given
6 list of integers in ascending order
i) Quick sort ii) Heap sort iii) Merge sort
Week 7
Write a program to implement the tree traversal methods (Recursive and Non
Recursive).
7
Week 8
Write a program to implement
8 i) Binary Search tree ii) B Trees iii) B+ Trees iv) AVL trees v) Red - Black trees
Week 9
Write a program to implement the graph traversal methods.
9
Week 10
10 Implement a Pattern matching algorithms using Boyer- Moore, Knuth-Morris-Pratt

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


SAMPLE PROGRAMS

#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int i;
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output: 1 2 3 4 5

1. Array Input and Printing


#include <stdio.h>
int main() {
int arr[5];
int i;
printf("Enter 5 elements: ");
for (i = 0; i < 5; i++) {
scanf("%d", &arr[i]);
}
printf("You entered: ");
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output: (Assuming user input: 10 20 30 40 50)
You entered: 10 20 30 40 50

1. Sum of Array Elements


#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int i, sum = 0;
for (i = 0; i < 5; i++) {

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


sum += arr[i];
}
printf("Sum of array elements: %d\n", sum);
return 0;
}
Output: Sum of array elements: 15

1. Array Reverse
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int i, temp;
printf("Original array: ");
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
for (i = 0; i < 5 / 2; i++) {
temp = arr[i];
arr[i] = arr[5 - i - 1];
arr[5 - i - 1] = temp;
}
printf("Reversed array: ");
for (i = 0; i < 5; i++) {
printf("%d ", arr[i]);
}
printf("\n");
return 0;
}
Output:
Original array: 1 2 3 4 5
Reversed array: 5 4 3 2 1

1. Array Search
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int i, target;
printf("Enter a number to search: ");
scanf("%d", &target);

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


for (i = 0; i < 5; i++) {
if (arr[i] == target) {
printf("%d found at position %d\n", target, i + 1);
return 0;
}
}
printf("%d not found in the array\n", target);
return 0;
}

1. Pointer Basics
#include <stdio.h>
int main() {
int var = 10;
int* ptr = &var;
printf("Value of var: %d\n", var);
printf("Address of var: %p\n", &var);
printf("Value of ptr: %p\n", ptr);
printf("Value at ptr: %d\n", *ptr);
return 0;
}
Output:
Value of var: 10
Address of var: 0x7fffcf4f4b4c
Value of ptr: 0x7fffcf4f4b4c
Value at ptr: 10

1. Pointer Arithmetic
#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int* ptr = arr;
printf("Value at ptr: %d\n", *ptr);
printf("Value at ptr + 1: %d\n", *(ptr + 1));
printf("Value at ptr + 2: %d\n", *(ptr + 2));
return 0;
}

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


Output:
Value at ptr: 1
Value at ptr + 1: 2
Value at ptr + 2: 3

1. Pointer Comparison
#include <stdio.h>
int main() {
int var1 = 10;
int var2 = 20;
int* ptr1 = &var1;
int* ptr2 = &var2;
if (ptr1 > ptr2) {
printf("ptr1 is greater than ptr2\n");
} else {
printf("ptr1 is less than or equal to ptr2\n");
}
return 0;
}
Output:
ptr1 is less than or equal to ptr2

1. Pointer and Arrays


#include <stdio.h>
int main() {
int arr[5] = {1, 2, 3, 4, 5};
int* ptr = arr;
for (int i = 0; i < 5; i++) {
printf("Value at index %d: %d\n", i, *(ptr + i));
}
return 0;
}
Output:
Value at index 0: 1
Value at index 1: 2
Value at index 2: 3
Value at index 3: 4
Value at index 4: 5

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


1. Pointer and Structures

#include <stdio.h>
struct Person {
int age;
char name[20];
};
int main() {
struct Person person = {25, "John"};
struct Person* ptr = &person;
printf("Age: %d\n", ptr->age);
printf("Name: %s\n", ptr->name);
return 0;
}
Output:
Age: 25
Name: John

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


Week1:
1 Write a program that uses functions to perform the following
operations on singly linked list:
i) Creation ii) Insertion iii) Deletion iv) Traversal
program:
#include <stdio.h>
#include <stdlib.h>

// Define the structure for a linked list node


typedef struct Node {
int data;
struct Node* next;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to create a linked list


void createList(Node** head) {

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


int data;
printf("Enter data (0 to stop): ");
scanf("%d", &data);
while (data != 0) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
printf("Enter data (0 to stop): ");
scanf("%d", &data);
}
}

// Function to insert a node at the beginning of the list


void insertAtBeginning(Node** head, int data) {
Node* newNode = createNode(data);
newNode->next = *head;
*head = newNode;
}

// Function to insert a node at the end of the list


void insertAtEnd(Node** head, int data) {

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next) {
current = current->next;
}
current->next = newNode;
}
}

// Function to delete a node from the list


void deleteNode(Node** head, int data) {
if (*head == NULL) return;
if ((*head)->data == data) {
Node* temp = *head;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
while (current->next) {
if (current->next->data == data) {
Node* temp = current->next;
current->next = current->next->next;
free(temp);
return;

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


}
current = current->next;
}
}

// Function to traverse the linked list


void traverse(Node* head) {
while (head) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}

int main() {
Node* head = NULL;
createList(&head);
printf("Linked List: ");
traverse(head);
insertAtBeginning(&head, 0);
insertAtEnd(&head, 4);
printf("Linked List after insertion: ");
traverse(head);
deleteNode(&head, 2);
printf("Linked List after deletion: ");
traverse(head);
return 0;
}

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


`Output:
Output:

Enter data (0 to stop): 1


Enter data (0 to stop): 2
Enter data (0 to stop): 3
Enter data (0 to stop): 0
Linked List: 1 2 3
After insertion:
Linked List: 0 1 2 3 4
After deletion:
Linked List: 0 1 3 4

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


Week 2:

2. Write a program that uses functions to perform the following


operations on doubly linked list:
i) Creation ii) Insertion iii) Deletion iv)Traversal
program:

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

// Define the structure for a doubly linked list node


typedef struct Node {
int data;
struct Node* next;
struct Node* prev;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
newNode->prev = NULL;
return newNode;
}

// Function to create a doubly linked list


void createList(Node** head) {
int data;

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


printf("Enter data (0 to stop): ");
scanf("%d", &data);
while (data != 0) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;
while (current->next) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
}
printf("Enter data (0 to stop): ");
scanf("%d", &data);
}
}

// Function to insert a node at the beginning of the list


void insertAtBeginning(Node** head, int data) {
Node* newNode = createNode(data);
newNode->next = *head;
if (*head)
(*head)->prev = newNode;
*head = newNode;
}

// Function to insert a node at the end of the list


void insertAtEnd(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
} else {
Node* current = *head;

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


while (current->next) {
current = current->next;
}
current->next = newNode;
newNode->prev = current;
}
}

// Function to delete a node from the list


void deleteNode(Node** head, int data) {
if (*head == NULL) return;
if ((*head)->data == data) {
Node* temp = *head;
*head = (*head)->next;
if (*head)
(*head)->prev = NULL;
free(temp);
return;
}
Node* current = *head;
while (current->next) {
if (current->next->data == data) {
Node* temp = current->next;
current->next = current->next->next;
if (current->next)
current->next->prev = current;
free(temp);
return;
}
current = current->next;
}
}

// Function to traverse the doubly linked list


void traverse(Node* head) {

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


printf("Linked List: ");
while (head) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}

int main() {
Node* head = NULL;
createList(&head);
traverse(head);
insertAtBeginning(&head, 0);
insertAtEnd(&head, 4);
printf("After insertion:\n");
traverse(head);
deleteNode(&head, 2);
printf("After deletion:\n");
traverse(head);
return 0;
}
Output:

Enter data (0 to stop): 1


Enter data (0 to stop): 2
Enter data (0 to stop): 3
Enter data (0 to stop): 0
Linked List: 1 2 3
After insertion:
Linked List: 0 1 2 3 4
After deletion:
Linked List: 0 1 3 4

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


Week 3:
3. Write a program that uses functions to perform the following
operations on circular linked list:
i) Creation ii) Insertion iii) Deletion iv) Traversal
program:

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

// Define the structure for a circular linked list node


typedef struct Node {
int data;
struct Node* next;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


// Function to create a circular linked list
void createList(Node** head) {
int data;
printf("Enter data (0 to stop): ");
scanf("%d", &data);
while (data != 0) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
(*head)->next = *head;
} else {
Node* current = *head;
while (current->next != *head) {
current = current->next;
}
current->next = newNode;
newNode->next = *head;
}
printf("Enter data (0 to stop): ");
scanf("%d", &data);
}
}

// Function to insert a node at the beginning of the list


void insertAtBeginning(Node** head, int data) {
Node* newNode = createNode(data);

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


if (*head == NULL) {
*head = newNode;
(*head)->next = *head;
} else {
Node* current = *head;
while (current->next != *head) {
current = current->next;
}
newNode->next = *head;
current->next = newNode;
*head = newNode;
}
}

// Function to insert a node at the end of the list


void insertAtEnd(Node** head, int data) {
Node* newNode = createNode(data);
if (*head == NULL) {
*head = newNode;
(*head)->next = *head;
} else {
Node* current = *head;
while (current->next != *head) {
current = current->next;
}
current->next = newNode;

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


newNode->next = *head;
}
}

// Function to delete a node from the list


void deleteNode(Node** head, int data) {
if (*head == NULL) return;
if ((*head)->data == data) {
Node* temp = *head;
Node* current = *head;
while (current->next != *head) {
current = current->next;
}
current->next = (*head)->next;
*head = (*head)->next;
free(temp);
return;
}
Node* current = *head;
while (current->next != *head) {
if (current->next->data == data) {
Node* temp = current->next;
current->next = current->next->next;
free(temp);
return;
}

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


current = current->next;
}
}

// Function to traverse the circular linked list


void traverse(Node* head) {
printf("Circular Linked List: ");
Node* current = head;
do {
printf("%d ", current->data);
current = current->next;
} while (current != head);
printf("\n");
}

int main() {
Node* head = NULL;
createList(&head);
traverse(head);
insertAtBeginning(&head, 0);
insertAtEnd(&head, 4);
printf("After insertion:\n");
traverse(head);
deleteNode(&head, 2);
printf("After deletion:\n");
traverse(head);

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


return 0;
}
Output:

Enter data (0 to stop): 1


Enter data (0 to stop): 2
Enter data (0 to stop): 3
Enter data (0 to stop): 0
Circular Linked List: 1 2 3
After insertion:
Circular Linked List: 0 1 2 3 4
After deletion:
Circular Linked List: 0 1 3 4

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


Week 4:

4. Write a program that implement stack (its operations) using


i) Arrays ii) Pointers
program:

#include <stdio.h>
// Array Implementation
#define MAX_SIZE 5
int stackArray[MAX_SIZE];
int topArray = -1;
void pushArray(int data) {
if (topArray == MAX_SIZE - 1) {
printf("Stack overflow\n");
return;
}
stackArray[++topArray] = data;
}
void popArray() {
if (topArray == -1) {
printf("Stack underflow\n");
return;
}
topArray--;
}
void displayArray() {
if (topArray == -1) {
printf("Stack is empty\n");
return;
}
printf("Stack (Array): ");
for (int i = 0; i <= topArray; i++) {
printf("%d ", stackArray[i]);
}
printf("\n");
}
// Pointer Implementation
typedef struct Node {
int data;
struct Node* next;

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


} Node;
Node* topPointer = NULL;
void pushPointer(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = topPointer;
topPointer = newNode;
}
void popPointer() {
if (topPointer == NULL) {
printf("Stack underflow\n");
return;
}
Node* temp = topPointer;
topPointer = topPointer->next;
free(temp);
}
void displayPointer() {
Node* current = topPointer;
printf("Stack (Pointer): ");
while (current) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
// Array Implementation
pushArray(1);
pushArray(2);
pushArray(3);
displayArray(); // Output: Stack (Array): 1 2 3
popArray();
displayArray(); // Output: Stack (Array): 1 2
// Pointer Implementation
pushPointer(1);
pushPointer(2);
pushPointer(3);
displayPointer(); // Output: Stack (Pointer): 3 2 1
popPointer();
displayPointer(); // Output: Stack (Pointer): 2 1
return 0;
}

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


Output:

Stack (Array): 1 2 3
Stack (Array): 1 2
Stack (Pointer): 3 2 1
Stack (Pointer): 2 1

Week:5
#include <stdio.h>
// Array Implementation
#define MAX_SIZE 5
int queueArray[MAX_SIZE];
int frontArray = 0;
int rearArray = -1;
int countArray = 0;
void enqueueArray(int data) {
if (countArray == MAX_SIZE) {
printf("Queue overflow\n");
return;
}
rearArray = (rearArray + 1) % MAX_SIZE;
queueArray[rearArray] = data;
countArray++;
}
void dequeueArray() {
if (countArray == 0) {
printf("Queue underflow\n");
return;
}
frontArray = (frontArray + 1) % MAX_SIZE;
countArray--;
}
void displayArray() {
if (countArray == 0) {
printf("Queue is empty\n");
return;
}
printf("Queue (Array): ");
int i = frontArray;

St.Mary’s Group of Institutions, Hyderabad Data Structures AIML DEPT


for (int j = 0; j < countArray; j++) {
printf("%d ", queueArray[i]);
i = (i + 1) % MAX_SIZE;
}
printf("\n");
}
// Pointer Implementation
typedef struct Node {
int data;
struct Node* next;
} Node;
Node* frontPointer = NULL;
Node* rearPointer = NULL;
void enqueuePointer(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->next = NULL;
if (rearPointer == NULL) {
frontPointer = newNode;
rearPointer = newNode;
} else {
rearPointer->next = newNode;
rearPointer = newNode;
}
}
void dequeuePointer() {
if (frontPointer == NULL) {
printf("Queue underflow\n");
return;
}
Node* temp = frontPointer;
frontPointer = frontPointer->next;
if (frontPointer == NULL) {
rearPointer = NULL;
}
free(temp);
}
void displayPointer() {
Node* current = frontPointer;
printf("Queue (Pointer): ");
while (current) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
int main() {
// Array Implementation
enqueueArray(1);
enqueueArray(2);
enqueueArray(3);
displayArray(); // Output: Queue (Array): 1 2 3
dequeueArray();
displayArray(); // Output: Queue (Array): 2 3
// Pointer Implementation
enqueuePointer(1);
enqueuePointer(2);
enqueuePointer(3);
displayPointer(); // Output: Queue (Pointer): 1 2 3
dequeuePointer();
displayPointer(); // Output: Queue (Pointer): 2 3
return 0;
}
Output:

Queue (Array): 1 2 3
Queue (Array): 2 3
Queue (Pointer): 1 2 3
Queue (Pointer): 2 3

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


Week:6
5. Write a program that implements the following sorting methods
to sort a given list of integers in ascending order
i) Quick sort ii) Heap sort iii) Merge sort

Program:
#include <stdio.h>
// Function to swap two elements
void swap(int* a, int* b) {
int temp = *a;
*a = *b;
*b = temp;
}

// Quick Sort
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pivot = arr[high];
int i = (low - 1);

for (int j = low; j <= high - 1; j++) {


if (arr[j] < pivot) {
i++;
swap(&arr[i], &arr[j]);
}
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
}
swap(&arr[i + 1], &arr[high]);
int pivotIndex = i + 1;
quickSort(arr, low, pivotIndex - 1);
quickSort(arr, pivotIndex + 1, high);
}
}

// Heap Sort
void heapify(int arr[], int n, int i) {
int largest = i;
int left = 2 * i + 1;
int right = 2 * i + 2;

if (left < n && arr[left] > arr[largest])


largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
swap(&arr[i], &arr[largest]);
heapify(arr, n, largest);
}
}

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


void heapSort(int arr[], int n) {
for (int i = n / 2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n - 1; i >= 0; i--) {
swap(&arr[0], &arr[i]);
heapify(arr, i, 0);
}
}

// Merge Sort
void merge(int arr[], int left, int mid, int right) {
int n1 = mid - left + 1;
int n2 = right - mid;

int leftArr[n1], rightArr[n2];

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


leftArr[i] = arr[left + i];
for (int j = 0; j < n2; j++)
rightArr[j] = arr[mid + 1 + j];
int i = 0, j = 0, k = left;

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


while (i < n1 && j < n2) {
if (leftArr[i] <= rightArr[j]) {
arr[k] = leftArr[i];
i++;
} else {
arr[k] = rightArr[j];
j++;
}
k++;
}

while (i < n1) {


arr[k] = leftArr[i];
i++;
k++;
}

while (j < n2) {


arr[k] = rightArr[j];
j++;
k++;
}
}

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


void mergeSort(int arr[], int left, int right) {
if (left < right) {
int mid = left + (right - left) / 2;

mergeSort(arr, left, mid);


mergeSort(arr, mid + 1, right);

merge(arr, left, mid, right);


}
}

// Function to print an array


void printArray(int arr[], int size) {
for (int i = 0; i < size; i++)
printf("%d ", arr[i]);
printf("\n");
}

// Driver code
int main() {
int arr[] = {64, 25, 12, 22, 11};
int n = sizeof(arr) / sizeof(arr[0]);

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


printf("Original array: \n");
printArray(arr, n);
// Quick Sort
quickSort(arr, 0, n - 1);
printf("Sorted array using Quick Sort: \n");
printArray(arr, n);

// Heap Sort
heapSort(arr, n);
printf("Sorted array using Heap Sort: \n");
printArray(arr, n);

// Merge Sort
mergeSort(arr, 0, n - 1);
printf("Sorted array using Merge Sort: \n");
printArray(arr, n);

return 0;
}

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


This program sorts the array {64, 25, 12, 22, 11} using Quick Sort, Heap
Sort, and Merge Sort. The output will be:

Original array:
64 25 12 22 11
Sorted array using Quick Sort:
11 12 22 25 64
Sorted array using Heap Sort:
11 12 22 25 64
Sorted array using Merge Sort:
11

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


Week:7
6. Write a program to implement the tree traversal methods(
Recursive and Non Recursive). Program:
#include <stdio.h>
#include <stdlib.h>

// Define the structure for a tree node


typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;

// Function to create a new node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

// Recursive tree traversal methods


void recursiveInorder(Node* root) {
if (root) {
recursiveInorder(root->left);
printf("%d ", root->data);
recursiveInorder(root->right);
}
}
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
void recursivePreorder(Node* root) {
if (root) {
printf("%d ", root->data);
recursivePreorder(root->left);
recursivePreorder(root->right);
}
}

void recursivePostorder(Node* root) {


if (root) {
recursivePostorder(root->left);
recursivePostorder(root->right);
printf("%d ", root->data);
}
}

// Non-Recursive tree traversal methods


void nonRecursiveInorder(Node* root) {
if (root) {
Node* current = root;
Node* prev = NULL;
while (current) {
if (!prev || prev->left == current || prev->right == current) {
if (current->left)
current = current->left;
else {
printf("%d ", current->data);
current = current->right;
}
} else {
printf("%d ", current->data);
current = current->right;
}
prev = current;
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
}
}
}

void nonRecursivePreorder(Node* root) {


if (root) {
Node* current = root;
while (current) {
printf("%d ", current->data);
if (current->left)
current = current->left;
else
current = current->right;
}
}
}

void nonRecursivePostorder(Node* root) {


if (root) {
Node* current = root;
Node* prev = NULL;
while (current) {
if (!prev || prev->left == current || prev->right == current) {
if (current->left)
current = current->left;
else if (current->right)
current = current->right;
else {
printf("%d ", current->data);
break;
}
} else {
if (prev->left == current) {
if (current->right)
current = current->right;
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
else {
printf("%d ", current->data);
break;
}
} else {
printf("%d ", current->data);
break;
}
}
prev = current;
}
}
}

int main() {
// Create a sample binary tree
Node* root = createNode(1);
root->left = createNode(2);
root->right = createNode(3);
root->left->left = createNode(4);
root->left->right = createNode(5);

// Recursive tree traversal


printf("Recursive Inorder: ");
recursiveInorder(root);
printf("\n");
printf("Recursive Preorder: ");
recursivePreorder(root);
printf("\n");
printf("Recursive Postorder: ");
recursivePostorder(root);
printf("\n");

// Non-Recursive tree traversal


printf("Non-Recursive Inorder: ");
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
nonRecursiveInorder(root);
printf("\n");
printf("Non-Recursive Preorder: ");
nonRecursivePreorder(root);
printf("\n");
printf("Non-Recursive Postorder: ");
nonRecursivePostorder(root);
printf("\n");

return 0;
}

Output:

Recursive Inorder: 4 2 5 1 3
Recursive Preorder: 1 2 4 5 3
Recursive Postorder: 4 5 2 3 1
Non-Recursive Inorder: 4 2 5 1 3
Non-Recursive Preorder: 1 2 4 5 3
Non-Recursive Postorder: 4 5 2 3 1

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


Week:8
7. Write a program to implement
i)Binary Search tree ii) B Trees iii) B+ Trees iv) AVL trees v) Red
- Black trees
1)Binary Search tree: Program:
#include <stdio.h>
#include <stdlib.h>
// Define the structure for a BST node
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
// Function to create a new node
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->left = newNode->right = NULL;

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


return newNode;
}
// Function to insert a node into the BST
Node* insertNode(Node* root, int data) {
if (root == NULL) {
root = createNode(data);
} else if (data < root->data) {
root->left = insertNode(root->left, data);
} else if (data > root->data) {
root->right = insertNode(root->right, data);
}
return root;
}
// Function to perform inorder traversal of the BST
void inorderTraversal(Node* root) {
if (root) {
inorderTraversal(root->left);
printf("%d ", root->data);
inorderTraversal(root->right);
}
}

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


// Function to search for a node in the BST
Node* searchNode(Node* root, int data) {
if (root == NULL || root->data == data) {
return root;
} else if (data < root->data) {
return searchNode(root->left, data);
} else {
return searchNode(root->right, data);
}
}
// Function to find the minimum value node in the BST
Node* findMinNode(Node* root) {
while (root->left != NULL) {
root = root->left;
}
return root;
}
// Function to delete a node from the BST
Node* deleteNode(Node* root, int data) {
if (root == NULL) {
return root;

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


} else if (data < root->data) {
root->left = deleteNode(root->left, data);
} else if (data > root->data) {
root->right = deleteNode(root->right, data);
} else {
if (root->left == NULL) {
Node* temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
Node* temp = root->left;
free(root);
return temp;
}
Node* temp = findMinNode(root->right);
root->data = temp->data;
root->right = deleteNode(root->right, temp->data);
}
return root;
}
int main() {

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


Node* root = NULL;
// Insert nodes into the BST
root = insertNode(root, 50);
root = insertNode(root, 30);
root = insertNode(root, 20);
root = insertNode(root, 40);
root = insertNode(root, 70);
root = insertNode(root, 60);
root = insertNode(root, 80);
// Perform inorder traversal of the BST
printf("Inorder Traversal: ");
inorderTraversal(root);
printf("\n");
// Search for a node in the BST
Node* searchedNode = searchNode(root, 40);
if (searchedNode) {
printf("Node found: %d\n", searchedNode->data);
} else {
printf("Node not found\n");
}
// Delete a node from the BST

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


root = deleteNode(root, 20);
// Perform inorder traversal of the BST after deletion
printf("Inorder Traversal after deletion: ");
inorderTraversal(root);
printf("\n");
return 0;
}
Output:
Inorder Traversal: 20 30 40 50 60 70 80
Node found: 40
Inorder Traversal after deletion: 30 40 50 60 70 80
ii)B Trees

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

// Define the structure for a B-Tree node


typedef struct Node {
int* keys;
struct Node** children;
int numKeys;
int leaf;
} Node;

// Function to create a new B-Tree node


Node* createNode(int leaf) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
printf("Memory error\n");
return NULL;
}
newNode->keys = (int*)malloc(sizeof(int) * 3);
newNode->children = (Node**)malloc(sizeof(Node*) * 4);
newNode->numKeys = 0;
newNode->leaf = leaf;
return newNode;
}

// Function to insert a key into the B-Tree


void insertKey(Node* root, int key) {
int i = 0;
while (i < root->numKeys && key > root->keys[i]) {
i++;
}
if (root->leaf) {
// Shift keys to make space for the new key
for (int j = root->numKeys; j > i; j--) {
root->keys[j] = root->keys[j - 1];
}
root->keys[i] = key;
root->numKeys++;
} else {
if (root->children[i]->numKeys == 3) {
// Split the child node
Node* newChild = createNode(0);
// Move keys to the new child node
for (int j = 1; j < 3; j++) {
newChild->keys[j - 1] = root->children[i]->keys[j];
root->children[i]->keys[j] = 0;
}
// Move children to the new child node
for (int j = 1; j < 4; j++) {
newChild->children[j - 1] = root->children[i]->children[j];
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
root->children[i]->children[j] = NULL;
}
root->children[i]->numKeys = 1;
newChild->numKeys = 2;
// Insert the key into the appropriate child node
if (key < root->children[i]->keys[0]) {
insertKey(root->children[i], key);
} else {
insertKey(newChild, key);
}
// Insert the new child node into the parent node
for (int j = root->numKeys; j > i; j--) {
root->keys[j] = root->keys[j - 1];
root->children[j + 1] = root->children[j];
}
root->keys[i] = root->children[i]->keys[0];
root->children[i + 1] = newChild;
root->numKeys++;
} else {
insertKey(root->children[i], key);
}
}
}

// Function to print the B-Tree


void printTree(Node* root, int level) {
if (root) {
for (int i = 0; i < level; i++) {
printf(" ");
}
for (int i = 0; i < root->numKeys; i++) {
printf("%d ", root->keys[i]);
}
printf("\n");
for (int i = 0; i <= root->numKeys; i++) {
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
printTree(root->children[i], level + 1);
}
}
}

int main() {
Node* root = createNode(1);

// Insert keys into the B-Tree


insertKey(root, 10);
insertKey(root, 20);
insertKey(root, 5);
insertKey(root, 6);
insertKey(root, 12);
insertKey(root, 30);
insertKey(root, 7);
insertKey(root, 17);

// Print the B-Tree


printf("B-Tree:\n");
printTree(root, 0);

return 0;
}

Output:
B-Tree:
10
57
6
12
17
20
30

St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir


ii)B+ tree:

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

// Define the structure for a B+ Tree node


typedef struct Node {
int* keys;
struct Node** children;
int numKeys;
int leaf;
} Node;

// Function to create a new B+ Tree node


Node* createNode(int leaf) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->keys = (int*)malloc(sizeof(int) * 3);
newNode->children = (Node**)malloc(sizeof(Node*) * 4);
newNode->numKeys = 0;
newNode->leaf = leaf;
return newNode;
}

// Function to insert a key into the B+ Tree


void insertKey(Node* root, int key) {
int i = 0;
while (i < root->numKeys && key > root->keys[i]) {
i++;
}
if (root->leaf) {
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
// Shift keys to make space for the new key
for (int j = root->numKeys; j > i; j--) {
root->keys[j] = root->keys[j - 1];
}
root->keys[i] = key;
root->numKeys++;
} else {
if (root->children[i]->numKeys == 3) {
// Split the child node
Node* newChild = createNode(0);
// Move keys to the new child node
for (int j = 1; j < 3; j++) {
newChild->keys[j - 1] = root->children[i]->keys[j];
root->children[i]->keys[j] = 0;
}
// Move children to the new child node
for (int j = 1; j < 4; j++) {
newChild->children[j - 1] = root->children[i]->children[j];
root->children[i]->children[j] = NULL;
}
root->children[i]->numKeys = 1;
newChild->numKeys = 2;
// Insert the key into the appropriate child node
if (key < root->children[i]->keys[0]) {
insertKey(root->children[i], key);
} else {
insertKey(newChild, key);
}
// Insert the new child node into the parent node
for (int j = root->numKeys; j > i; j--) {
root->keys[j] = root->keys[j - 1];
root->children[j + 1] = root->children[j];
}
root->keys[i] = root->children[i]->keys[0];
root->children[i + 1] = newChild;
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
root->numKeys++;
} else {
insertKey(root->children[i], key);
}
}
}

// Function to print the B+ Tree


void printTree(Node* root, int level) {
if (root) {
for (int i = 0; i < level; i++) {
printf(" ");
}
for (int i = 0; i < root->numKeys; i++) {
printf("%d ", root->keys[i]);
}
printf("\n");
for (int i = 0; i <= root->numKeys; i++) {
printTree(root->children[i], level + 1);
}
}
}

int main() {
Node* root = createNode(1);

// Insert keys into the B+ Tree


insertKey(root, 10);
insertKey(root, 20);
insertKey(root, 5);
insertKey(root, 6);
insertKey(root, 12);
insertKey(root, 30);
insertKey(root, 7);
insertKey(root, 17);
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
// Print the B+ Tree
printf("B+ Tree:\n");
printTree(root, 0);

return 0;
}

Output:

B+ Tree:
10
57
6
12
17
20
30

iv) AVL TREE


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

// Define the structure for an AVL Tree node


typedef struct Node {
int data;
struct Node* left;
struct Node* right;
int height;
} Node;
St.Mary’s Group of Institutions, Hyderabad Data Structures Nagarjun Sir
// Function to create a new AVL Tree node
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->left = newNode->right = NULL;
newNode->height = 1;
return newNode;
}

// Function to get the height of an AVL Tree node


int getHeight(Node* node) {
if (node == NULL) {
return 0;
}
return node->height;
}

// Function to update the height of an AVL Tree node


void updateHeight(Node* node) {
node->height = 1 + (getHeight(node->left) > getHeight(node->right) ?
getHeight(node->left) : getHeight(node->right));
}

// Function to get the balance factor of an AVL Tree node


int getBalance(Node* node) {
if (node == NULL) {
return 0;
}
return getHeight(node->left) - getHeight(node->right);
}
43
// Function to perform a left rotation in the AVL Tree
Node* leftRotate(Node* node) {
Node* temp = node->right;
node->right = temp->left;
temp->left = node;
updateHeight(node);
updateHeight(temp);
return temp;
}

// Function to perform a right rotation in the AVL Tree


Node* rightRotate(Node* node) {
Node* temp = node->left;
node->left = temp->right;
temp->right = node;
updateHeight(node);
updateHeight(temp);
return temp;
}

// Function to rebalance the AVL Tree


Node* rebalance(Node* node) {
int balance = getBalance(node);
if (balance > 1) {
if (getHeight(node->left->left) >= getHeight(node->left->right)) {
node = rightRotate(node);
} else {
node->left = leftRotate(node->left);
node = rightRotate(node);
}
} else if (balance < -1) {
if (getHeight(node->right->right) >= getHeight(node->right->left))
{
node = leftRotate(node);
44
} else {
node->right = rightRotate(node->right);
node = leftRotate(node);
}
}
return node;
}

// Function to insert a node into the AVL Tree


Node* insertNode(Node* node, int data) {
if (node == NULL) {
return createNode(data);
} else if (data < node->data) {
node->left = insertNode(node->left, data);
} else if (data > node->data) {
node->right = insertNode(node->right, data);
} else {
return node;
}
updateHeight(node);
return rebalance(node);
}

// Function to print the AVL Tree


void printTree(Node* node, int level) {
if (node) {
printTree(node->right, level + 1);
for (int i = 0; i < level; i++) {
printf(" ");
}
printf("%d\n", node->data);
printTree(node->left, level + 1);
}
}

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

// Insert nodes into the AVL Tree


root = insertNode(root, 10);
root = insertNode(root, 20);
root = insertNode(root, 5);
root = insertNode(root, 6);
root = insertNode(root, 12);
root = insertNode(root, 30);
root = insertNode(root, 7);
root = insertNode(root, 17);

// Print the AVL Tree


printf("AVL Tree:\n");
printTree(root, 0);

return 0;
}

Output:

AVL Tree:
20
12
10
6
5
7
17
30

46
9)Write a program to implement the graph traversal methods.

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

// Define the structure for a graph node


typedef struct Node {
int data;
struct Node* next;
} Node;

// Define the structure for a graph


typedef struct Graph {
int numVertices;
Node** adjLists;
} Graph;

// Function to create a new graph node


Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
if (!newNode) {
printf("Memory error\n");
return NULL;
}
newNode->data = data;
newNode->next = NULL;
return newNode;
}

// Function to create a new graph


Graph* createGraph(int numVertices) {
Graph* newGraph = (Graph*)malloc(sizeof(Graph));
if (!newGraph) {
printf("Memory error\n");
return NULL;
47
}
newGraph->numVertices = numVertices;
newGraph->adjLists = (Node**)malloc(sizeof(Node*) *
numVertices);
for (int i = 0; i < numVertices; i++) {
newGraph->adjLists[i] = NULL;
}
return newGraph;
}

// Function to add an edge to the graph


void addEdge(Graph* graph, int src, int dest) {
Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;
}

// Function to perform BFS traversal


void BFS(Graph* graph, int startVertex) {
int visited[graph->numVertices];
for (int i = 0; i < graph->numVertices; i++) {
visited[i] = 0;
}
Node* queue[graph->numVertices];
int front = 0, rear = 0;
queue[rear++] = graph->adjLists[startVertex];
visited[startVertex] = 1;
while (front < rear) {
Node* temp = queue[front++];
printf("%d ", temp->data);
Node* adjList = graph->adjLists[temp->data];
while (adjList) {
if (!visited[adjList->data]) {
queue[rear++] = adjList;
visited[adjList->data] = 1;
48
}
adjList = adjList->next;
}
}
}

// Function to perform DFS traversal


void DFS(Graph* graph, int startVertex) {
int visited[graph->numVertices];
for (int i = 0; i < graph->numVertices; i++) {
visited[i] = 0;
}
DFSUtil(graph, startVertex, visited);
}

// Helper function for DFS traversal


void DFSUtil(Graph* graph, int vertex, int* visited) {
visited[vertex] = 1;
printf("%d ", vertex);
Node* adjList = graph->adjLists[vertex];
while (adjList) {
if (!visited[adjList->data]) {
DFSUtil(graph, adjList->data, visited);
}
adjList = adjList->next;
}
}

int main() {
Graph* graph = createGraph(6);
addEdge(graph, 0, 1);
addEdge(graph, 0, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 5);
49
printf("BFS Traversal: ");
BFS(graph, 0);
printf("\n");
printf("DFS Traversal: ");
DFS(graph, 0);
printf("\n");
return 0;
}

Output:

BFS Traversal: 0 1 2 3 4 5
DFS Traversal: 0 1 3 4 2 5

50
10) Implement a Pattern matching algorithms using Boyer- Moore,
Knuth-Morris-Pratt

#include <stdio.h>
#include <string.h>

// Boyer-Moore Algorithm
void boyerMoore(char* text, char* pattern) {
int n = strlen(text);
int m = strlen(pattern);
int i = m - 1;
int j = m - 1;

while (i < n) {
if (text[i] == pattern[j]) {
if (j == 0) {
printf("Pattern found at position %d\n", i);
return;
}
i--;
j--;
} else {
i = i + m - min(j, 1 + i - m);
j = m - 1;
}
}
printf("Pattern not found\n");
}

// Knuth-Morris-Pratt Algorithm
void knuthMorrisPratt(char* text, char* pattern) {
int n = strlen(text);
int m = strlen(pattern);
int lps[m];
int j = 0;
51
computeLPSArray(pattern, m, lps);

int i = 0;
while (i < n) {
if (pattern[j] == text[i]) {
j++;
i++;
}
if (j == m) {
printf("Pattern found at position %d\n", i - j);
j = lps[j - 1];
} else if (i < n && pattern[j] != text[i]) {
if (j != 0)
j = lps[j - 1];
else
i = i + 1;
}
}
printf("Pattern not found\n");
}

// Compute LPS (Longest Prefix Suffix) array for KMP


void computeLPSArray(char* pattern, int m, int* lps) {
int len = 0;
lps[0] = 0;
int i = 1;

while (i < m) {
if (pattern[i] == pattern[len]) {
len++;
lps[i] = len;
i++;
} else {
if (len != 0) {
52
len = lps[len - 1];
} else {
lps[i] = 0;
i++;
}
}
}
}

// Driver code
int main() {
char text[] = "ABABDABACDABABCABAB";
char pattern[] = "ABABCABAB";

printf("Boyer-Moore Algorithm:\n");
boyerMoore(text, pattern);

printf("Knuth-Morris-Pratt Algorithm:\n");
knuthMorrisPratt(text, pattern);

return 0;
}

Output:

Boyer-Moore Algorithm:
Pattern found at position 10
Knuth-Morris-Pratt Algorithm:
Pattern found at position 10

53
1) What is data structure?
Data structure refers to the way data is organized and
manipulated. It seeks to find ways to make data access more
efficient. When dealing with the data structure, we not only focus
on one piece of data but the different set of data and how they can
relate to one another in an organized manner.

2) Differentiate between file and structure storage structure.


The key difference between both the data structure is the memory
area that is being accessed. When dealing with the structure that
resides the main memory of the computer system, this is referred
to as storage structure. When dealing with an auxiliary structure,
we refer to it as file structures.

3) When is a binary search best applied?


A binary search is an algorithm that is best applied to search a list
when the elements are already in order or sorted. The list is
searched starting in the middle, such that if that middle value is
not the target search key, it will check to see if it will continue the
search on the lower half of the list or the higher half. The split and
search will then continue in the same manner.

54
4) What is a linked list?
A linked list is a sequence of nodes in which each node is
connected to the node following it. This forms a chain-like link
for data storage.

5) How do you reference all the elements in a one-dimension array?


To reference all the elements in an one -dimension array, you need
to use an indexed loop, So that, the counter runs from 0 to the
array size minus one. In this manner, You can reference all the
elements in sequence by using the loop counter as the array
subscript.

6) In what areas do data structures are applied?


Data structures are essential in almost every aspect where data is
involved. In general, algorithms that involve efficient data structure
is applied in the following areas: numerical analysis, operating
system, A.I., compiler design, database management, graphics, and
statistical analysis, to name a few.
7) What is LIFO?

LIFO is a short form of Last In First Out. It refers how data is


accessed, stored and retrieved. Using this scheme, data that was
stored last should be the one to be extracted first. This also means
that in order to gain access to the first data, all the other data that
was stored before this first data must first be retrieved and

55
extracted.

8) What is a queue?
A queue is a data structure that can simulate a list or stream of
data. In this structure, new elements are inserted at one end, and
existing elements are removed from the other end.

9) What are binary trees?


A binary tree is one type of data structure that has two nodes, a
left node, and a right node. In programming, binary trees are an
extension of the linked list structures.

10) Which data structures are applied when dealing with a recursive
function?
Recursion, is a function that calls itself based on a terminating
condition, makes use of the stack. Using LIFO, a call to a
recursive function saves the return address so that it knows how to
return to the calling function after the call terminates.

11) What is a stack?


A stack is a data structure in which only the top element can be
accessed. As data is stored in the stack, each data is pushed
downward, leaving the most recently added data on top.

12) Explain Binary Search Tree


56
A binary search tree stores data in such a way that they can be
retrieved very efficiently. The left subtree contains nodes whose
keys are less than the node’s key value, while the right subtree
contains nodes whose keys are greater than or equal to the node’s
key value. Moreover, both subtrees are also binary search trees.
13) What are multidimensional arrays?
Multidimensional arrays make use of multiple indexes to store data.
It is useful when storing data that cannot be represented using
single dimensional indexing, such as data representation in a board
game, tables with data stored in more than one column.

14) Are linked lists considered linear or non-linear data structures?


It depends on where you intend to apply linked lists. If you based it
on storage, a linked list is considered non-linear. On the other
hand, if you based it on access strategies, then a linked list is
considered linear.

15) How does dynamic memory allocation help in managing data?


Apart from being able to store simple structured data types,
dynamic memory allocation can combine separately allocated
structured blocks to form composite structures that expand and
contract as needed.

16) What is FIFO?


57
FIFO stands for First-in, First-out, and is used to represent how
data is accessed in a queue. Data has been inserted into the queue
list the longest is the one that is removed first.

17) What is an ordered list?


An ordered list is a list in which each node’s position in the list is
determined by the value of its key component, so that the key
values form an increasing sequence, as the list is traversed.

18) What is merge sort?


Merge sort, is a divide-and-conquer approach for sorting the data.
In a sequence of data, adjacent ones are merged and sorted to
create bigger sorted lists. These sorted lists are then merged again
to form an even bigger sorted list, which continues until you have
one single sorted list.

19) Differentiate NULL and VOID


Null is a value, whereas Void is a data type identifier. A variable
that is given a Null value indicates an empty value. The void is
used to identify pointers as having no initial size.

20) What is the primary advantage of a linked list?


A linked list is an ideal data structure because it can be modified
easily. This means that editing a linked list works regardless of

58
how many elements are in the list.

21) What is the difference between a PUSH and a POP?


Pushing and popping applies to the way data is stored and retrieved
in a stack. A push denotes data being added to it, meaning data is
being “pushed” into the stack. On the other hand, a pop denotes
data retrieval, and in particular, refers to the topmost data being
accessed.

22) What is a linear search?


A linear search refers to the way a target key is being searched in a
sequential data structure. In this method, each element in the list
is checked and compared against the target key. The process is
repeated until found or if the end of the file has been reached.

23) How does variable declaration affect memory allocation?


The amount of memory to be allocated or reserved would depend on
the data type of the variable being declared. For example, if a
variable is declared to be of integer type, then 32 bits of memory
storage will be reserved for that variable.

24) What is the advantage of the heap over a stack?


The heap is more flexible than the stack. That’s because memory
59
space for the heap can bedynamically allocated and de-allocated as
needed. However, the memory of the heap can at times be slower
when compared to that stack.

25) What is a postfix expression?


A postfix expression is an expression in which each operator
follows its operands. The advantage of this form is that there is no
need to group sub-expressions in parentheses or to consider
operator precedence.

26) What is Data abstraction?


Data abstraction is a powerful tool for breaking down complex data
problems into manageable chunks. This is applied by initially
specifying the data objects involved and the operations to be
performed on these data objects without being overly concerned
with how the data objects will be represented and stored in
memory.

27) How do you insert a new item in a binary search tree?


Assuming that the data to be inserted is a unique value (that is, not
an existing entry in the tree), check first if the tree is empty. If it’s
empty, just insert the new item in the root node. If it’s not empty,
refer to the new item’s key. If it’s smaller than the root’s key,
insert it into the root’s left subtree, otherwise, insert it into the
60
root’s right subtree.

28) How does a selection sort work for an array?


The selection sort is a fairly intuitive sorting algorithm, though not
necessarily efficient. In this process, the smallest element is first
located and switched with the element at subscript zero, thereby
placing the smallest element in the first position.
The smallest element remaining in the subarray is then located next
to subscripts 1 through n-1 and switched with the element at
subscript 1, thereby placing the second smallest element in the
second position. The steps are repeated in the same manner till the
last element.

29) How do signed and unsigned numbers affect memory?


In the case of signed numbers, the first bit is used to indicate
whether positive or negative, which leaves you with one bit short.
With unsigned numbers, you have all bits available for that
number. The effect is best seen in the number range (an unsigned
8-bit number has a range 0-255, while the 8-bit signed number has
a range -128 to +127.

30) What is the minimum number of nodes that a binary tree can
have?
A binary tree can have a minimum of zero nodes, which occurs

61
when the nodes have NULL values. Furthermore, a binary tree
can also have 1 or 2 nodes.

31) What are dynamic data structures?


Dynamic data structures are structures that expand and contract as
a program runs. It provides a flexible means of manipulating data
because it can adjust according to the size of the data.

32) In what data structures are pointers applied?


Pointers that are used in linked list have various applications in the
data structure. Data structures that make use of this concept
include the Stack, Queue, Linked List and Binary Tree.

33) Do all declaration statements result in a fixed reservation in


memory?
Most declarations do, with the exemption of pointers. Pointer
declaration does not allocate memory for data, but for the address
of the pointer variable. Actual memory allocation for the data
comes during run-time.

34) What are ARRAYs?


When dealing with arrays, data is stored and retrieved using an
index that refers to the element number in the data sequence. This
means that data can be accessed in any order. In programming,
anarray is declared as a variable having a number of indexed
62
elements.

35) What is the minimum number of queues needed when


implementing a priority queue?
The minimum number of queues needed in this case is two. One
queue is intended for sorting priorities while the other queue is
used for actual storage of data.

36) Which sorting algorithm is considered the fastest?


There are many types of sorting algorithms: quick sort, bubble sort,
balloon sort, radix sort, merge sort, etc. Not one can be considered
the fastest because each algorithm is designed for a particular data
structure and data set. It would depend on the data set that you
would want to sort.

37) Differentiate STACK from ARRAY.


Stack follows a LIFO pattern. It means that data access follows a
sequence wherein the last data to be stored when the first one to
be extracted. Arrays, on the other hand, does not follow a
particular order and instead can be accessed by referring to the
indexed element within the array.

38) Give a basic algorithm for searching a binary search tree.


if the tree is empty, then the target is not in the tree, end search

63
1. if the tree is not empty, the target is in the tree
2. check if the target is in the root item
3. if a target is not in the root item, check if a target is smaller
than the root’s value
4. if a target is smaller than the root’s value, search the left
subtree
5. else, search the right subtree

39) What is a dequeue?


A dequeue is a double-ended queue. This is a structure wherein
elements can be inserted or removed from either end.

40) What is a bubble sort and how do you perform it?


A bubble sort is one sorting technique that can be applied to data
structures such as an array. It works by comparing adjacent
elements and exchanges their values if they are out of order.
This method lets the smaller values “bubble” to the top of the
list, while the larger value sinks to the bottom.

41) What are the parts of a linked list?


A linked list typically has two parts: the head and the tail.
Between the head and tail lie the actual nodes. All these nodes
are linked sequentially.

64

You might also like