0% found this document useful (0 votes)
33 views48 pages

DSA Lab CIA 2

The document describes a C program for operations on a binary search tree. It includes functions to insert, search, delete, find minimum and maximum nodes, and traverse the tree using inorder, preorder and postorder traversal. It also contains code to test the functions.

Uploaded by

NOSSAM BHARGAVI
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)
33 views48 pages

DSA Lab CIA 2

The document describes a C program for operations on a binary search tree. It includes functions to insert, search, delete, find minimum and maximum nodes, and traverse the tree using inorder, preorder and postorder traversal. It also contains code to test the functions.

Uploaded by

NOSSAM BHARGAVI
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/ 48

C Program 06-03-2024 (DSA)

1. Write a C program of Operations on Binary Search Tree

Source Code:

/* Surianandhan S
127018060
CSBS 2nd Semester
06-03-2024
Binary Search Tree (BST) */

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

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

struct Node *getNode(int data) {


struct Node *newNode = (struct Node *)malloc(sizeof(struct Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}

struct Node *insertBST(struct Node *root, int x) {


if (root == NULL) {
return getNode(x);
}

if (x < root->data) {
root->left = insertBST(root->left, x);
} else if (x > root->data) {
root->right = insertBST(root->right, x);
} else {
printf("Duplicate value. Cannot insert.\n");
}
return root;
}

void inorder(struct Node *root) {


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

void preorder(struct Node *root) {


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

void postorder(struct Node *root) {


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

int minimum(struct Node *root) {


if (root == NULL) {
printf("Error: Empty tree.\n");
return -1;
}

while (root->left != NULL) {


root = root->left;
}

return root->data;
}
int maximum(struct Node *root) {
if (root == NULL) {
printf("Error: Empty tree.\n");
return -1;
}

while (root->right != NULL) {


root = root->right;
}

return root->data;
}

struct Node *searchBST(struct Node *root, int x) {


if (root == NULL) {
return NULL;
}

if (x < root->data) {
return searchBST(root->left, x);
} else if (x > root->data) {
return searchBST(root->right, x);
} else {
return root;
}
}

struct Node *deleteBST(struct Node *root, int x) {


if (root == NULL) {
printf("Element not found. Deletion cannot be performed.\n");
return root;
}

if (x < root->data) {
root->left = deleteBST(root->left, x);
} else if (x > root->data) {
root->right = deleteBST(root->right, x);
} else {
if (root->left == NULL) {
struct Node *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct Node *temp = root->left;
free(root);
return temp;
}

struct Node *temp = minimum(root->right);


root->data = temp->data;
root->right = deleteBST(root->right, temp->data);
}

return root;
}

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

int n, value;
printf("Enter Number of Data to be Inserted: ");
scanf("%d", &n);
for (int i=0; i<n; i++) {
printf("Enter Value to be Inserted: ");
scanf("%d", &value);
root = insertBST(root, value);
}

printf("Inorder traversal: ");


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

printf("Preorder traversal: ");


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

printf("Postorder traversal: ");


postorder(root);
printf("\n");
int choice;
int key, minVal, maxVal, del;
while (1) {
printf("\nMenu:\n");
printf("1. Search Value\n");
printf("2. Delete Value\n");
printf("0. Exit\n");

printf("Enter your choice: ");


scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter Element to Search: ");
scanf("%d", &key);
struct Node *found = searchBST(root, key);
if (found) {
printf("Element %d found\n", found->data);
} else {
printf("Element NOT found\n");
}
minVal = minimum(root);
maxVal = maximum(root);
printf("Minimum Value: %d\n", minVal);
printf("Maximum Value: %d\n", maxVal);
break;
case 2:
printf("Enter Element to Delete: ");
scanf("%d", &del);
root = deleteBST(root, del);
printf("Inorder Traversal After Deletion: ");
inorder(root);
printf("\n");
break;
case 0:
exit(0);
default:
printf("Invalid Choice.\n");
}
}
printf("\n");
return 0;
}

OUTPUT:

Enter Number of Data to be Inserted: 5


Enter Value to be Inserted: 1
Enter Value to be Inserted: 2
Enter Value to be Inserted: 3
Enter Value to be Inserted: 4
Enter Value to be Inserted: 5
Inorder traversal: 1 2 3 4 5
Preorder traversal: 1 2 3 4 5
Postorder traversal: 5 4 3 2 1

Menu:
1. Search Value
2. Delete Value
0. Exit
Enter your choice: 1
Enter Element to Search: 3
Element 3 found
Minimum value: 1
Maximum value: 5

Menu:
1. Search Value
2. Delete Value
0. Exit
Enter your choice: 2
Enter Element to Deleted: 4
Inorder traversal after deletion: 1 2 3 5

Menu:
1. Search Value
2. Delete Value
0. Exit
Enter your choice: 2
Enter Element to Deleted: 5
Inorder traversal after deletion: 1 2 3

Menu:
1. Search Value
2. Delete Value
0. Exit
Enter your choice: 1
Enter Element to Search: 4
Element not found
Minimum value: 1
Maximum value: 3

Menu:
1. Search Value
2. Delete Value
0. Exit
Enter your choice: 0
C Program 06-03-2024 (DSA)

Write a C program of Operations on Line Editor

Source Code:

/* Surianandhan S
127018060
CSBS 2nd Semester
06-03-2024
Line Editor */

1. LEdit.c

#include <stdio.h>
#include "Editor.c"
#define MAX_LEN 80
int main()
{
int op;
int lcount=0, lno;
char line[100], filename[25], word[25], rword[25];
char *t;
HEAD *head=NULL;
do
{
printf("\n1. New File\n2. Read from file\n3. Save to file\n4. Display Contents");
printf("\n5. Insert a new line\n6. Find word\n7. Delete a line");
printf("\nEnter your option: ");
scanf("%d", &op);
switch(op)
{
case 1: getchar();
head = createHead();
lcount = 0;
do
{
printf("\n%d. ",++lcount);
if (gets(line)!= NULL)
{
if (strcmp(line, "END")==0)
break;
Append(head, line);
}
}
while (!feof(stdin));
break;
case 2: printf("\nEnter filename : ");
scanf("%s", filename);
head = Read_From_File(filename);
break;
case 3: if (head != NULL)
{
printf("\nEnter filename : ");
scanf("%s", filename);
Save_To_File(head, filename);
}
break;
case 4: if (head != NULL)
{
printf("\nCurrent contents : \n");
Display(head);
}
break;
case 5: if (head != NULL)
{
printf("Enter the line number : ");
scanf("%d", &lno);
getchar();
printf("Enter the text to insert : ");
if (gets(line) != NULL)
Insert_At_Loc(head, lno, line);
}
break;
case 6: if (head != NULL)
{
printf("Enter the word to search : ");
scanf("%s", word);
Find(head, word);
}
break;
case 7: if (head != NULL)
{
printf("Enter the line number to delete : ");
scanf("%d", &lno);
Delete_At_Loc(head,lno);
}
break;
}
}
while(op <= 7);
return 0;
}

2. dll.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dlltype.h"

HEAD *createHead()
{
HEAD *head = (HEAD *) malloc(sizeof(HEAD));
head->start = head->end = NULL;
head->LC = head->TWC = 0;
return head;
}
void Append(HEAD *head, char line[100])
{
int i, k, WC=0;
char word[20];
LINEHEAD *lh;
NODE *last;
NODE *nn;
lh = (LINEHEAD *)malloc(sizeof(LINEHEAD));
lh->P = lh->N =NULL;
lh->first = NULL;
lh->WC = 0;
if (head->end == NULL){
head->start = head->end = lh;
lh->P = lh;
lh->N = lh;
}
else
{
lh->P = head->end;
lh->N = head->end->N;
head->end->N = lh;
head->end = lh;
head->start->P = lh;
}

i=0;
while (line[i]!='\0'){
k = 0;
while (!isspace(line[i]))
{
word[k++]=line[i++];
if (line[i]=='\0') break;
}
word[k]='\0';
(lh->WC)++;
nn = (NODE*)malloc(sizeof(NODE));
nn->next = nn->prev = NULL;
strcpy(nn->word,word);
if (lh->first == NULL)
{
lh->first = nn;
nn->prev = nn->next = NULL;
last = nn;
}
else
{
nn->prev = last;
last->next = nn;
last = nn;
}
while (isspace(line[i])) i++;
}
head->TWC += lh->WC;
(head->LC)++;
}

void Insert_At_Loc(HEAD *head, int loc, char line[100])


{
int len, i, WC=0;
char word[20];
LINEHEAD *cur_line;
NODE *nn, *last=NULL;
int k;
LINEHEAD *lh = (LINEHEAD *)malloc(sizeof(LINEHEAD));
lh->P = lh->N = NULL;
lh->first = NULL;
lh->WC = 0;
i=0;
while (line[i]!='\0'){
k = 0;
while (!isspace(line[i]))
{
word[k++]=line[i++];
if (line[i]=='\0') break;
}
word[k]='\0';
(lh->WC)++;
nn = (NODE*)malloc(sizeof(NODE));
nn->next = nn->prev = NULL;
strcpy(nn->word,word);
if (lh->first == NULL)
{
lh->first = nn;
nn->prev = nn->next = NULL;
last = nn;
}
else
{
nn->prev = last;
last->next = nn;
last = nn;
}
while (isspace(line[i])) i++;
}
if (loc==1){
lh->P = head->end;
lh->N = head->start;
head->start->P = lh;
head->end->N = lh;
head->start = lh;
}
else{
cur_line = head->start;
k=1;
while (k<loc-1 && cur_line->N!=head->start){
cur_line = cur_line->N;
k++;
}
lh->P = cur_line;
lh->N = cur_line->N;
cur_line->N->P = lh;
cur_line->N = lh;
if (head->end == cur_line)
head->end = lh;
}
head->TWC += lh->WC;
(head->LC)++;
return;
}

void Delete_At_Loc(HEAD *head, int loc)


{
int i=1;
LINEHEAD *cur_line;
if (head->start == NULL){
printf("\nEmpty Text.");
return;
}
if (head->LC < loc)
{
printf("No such line exists in the text.");
return;
}
cur_line = head->start;
while (cur_line != head->end && i < loc)
{
cur_line = cur_line->N;
i++;
}
if (cur_line->P != head->end)
cur_line->P->N = cur_line->N;
else
head->start = cur_line->N;
if (cur_line->N != head->start)
cur_line->N->P = cur_line->P;
else
head->end = cur_line->P;
head->LC--;
head->TWC -= cur_line->WC;
NODE *cur_word = cur_line->first;
while (cur_word != NULL){
NODE *t = cur_word;
cur_word = cur_word->next;
free(t);
}
free(cur_line);
return;
}
void Find(HEAD *head, char word[])
{
int flag = 0, pos;
LINEHEAD *cur_line;
NODE *cur_word;
int i = 1;
if (head->start == NULL)
{
printf("\nEmpty text");
return;
}

cur_line = head->start;
while (cur_line != head->end)
{
pos = 0;
cur_word = cur_line->first;
while (cur_word != NULL)
{
pos++;
if (strcmp(cur_word->word, word) == 0)
{
flag = 1;
printf("\nOccurrence of %s is in Line - %d at position %d", word, i, pos);
}
cur_word = cur_word->next;
}
cur_line = cur_line->N;
i++;
}
cur_word = head->end->first;
pos = 0;
while (cur_word != NULL)
{
pos++;
if (strcmp(cur_word->word, word) == 0)
{
flag = 1;
printf("\nOccurrence of %s is in Line - %d at position %d", word, i, pos);
}
cur_word = cur_word->next;
}
if (!flag)
printf("\n%s is not present in the text.", word);
}
void Display(HEAD *head)
{
int i;
LINEHEAD *lh = head->start;
i=1;
while (lh!= head->end){

NODE *cur = lh->first;


printf("\n%d. ", i);
while (cur != NULL)
{
printf("%s ", cur->word);
cur = cur->next;
}
i++;
lh = lh->N;
}
NODE *cur = lh->first;
printf("\n%d. ", i);
while (cur != NULL)
{
printf("%s ", cur->word);
cur = cur->next;
}
printf("\nNo. of lines = %d \nNo. of words = %d\n", head->LC, head->TWC);
}

3. dlltype.h

#ifndef DLLTYPE_H
#define DLLTYPE_H
typedef struct
{
struct linehead *start;
int LC;
int TWC;
struct linehead *end;
}HEAD;

typedef struct linehead


{
struct linehead *P;
int WC;
struct dllnode *first;
struct linehead *N;
}LINEHEAD;

typedef struct dllnode


{
struct dllnode *prev;
char word[20];
struct dllnode *next;
}NODE;

HEAD* createHead();
void Append(HEAD *head, char line[]);
void Insert_At_Loc(HEAD *head, int loc, char *line);
void Delete_At_Loc(HEAD *head, int loc);
void Find(HEAD *head, char word[]);
void Display(HEAD *head);
#endif

4. Editor.c

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "Editor.h"
#include "dll.c"
#define MAX_LEN 80

HEAD *Read_From_File(char filename[])


{
int i;
char line[100];
FILE *fp = fopen(filename, "r");
HEAD *head = createHead();
do
{
fgets(line, MAX_LEN, fp);
if (!feof(fp))
Append(head, line);
}
while (!feof(fp));
fclose(fp);
return head;
}

void Save_To_File(HEAD *head, char filename[])


{
int i;
FILE *fp = fopen(filename, "w");
LINEHEAD *cur = head->start;
while (cur != head->end)
{
NODE *cur_word = cur->first;
while (cur_word != NULL){
fprintf(fp, "%s ", cur_word->word);
cur_word = cur_word->next;
}
cur = cur->N;
fprintf(fp, "\n");
}
NODE *cur_word = cur->first;
while (cur_word != NULL){
fprintf(fp, "%s ", cur_word->word);
cur_word = cur_word->next;
}
fprintf(fp,"\n");
fclose(fp);
}

5. Editor.h

#include "dlltype.h"
HEAD *Read_From_File(char filename[]);
void Save_To_File(HEAD *head, char filename[]);

OUTPUT:
1. New File
2. Read from file
3. Save to file
4. Display Contents
5. Insert a new line
6. Find word
7. Delete a line
Enter your option: 1
(Entering lines...)

Enter your option: 4

Current contents:
1. Line 1
2. Line 2
3. Line 3

No. of lines = 3
No. of words = 9

Enter your option: 5

Enter the line number: 2


Enter the text to insert: Inserted line

(Updating lines...)

Enter your option: 6

Enter the word to search: Line

Occurrences found.

Enter your option: 7

Enter the line number to delete: 2

(Deleting line...)

Enter your option: 3

Enter filename: output.txt

Enter your option: 4

Current contents:
1. Line 1
2. Line 3

No. of lines = 2
No. of words = 6

Enter your option: 2

Enter filename: output.txt

Enter your option: 4

Current contents:
1. Line 1
2. Line 3

No. of lines = 2
No. of words = 6

Enter your option: 8


C Program 27-03-2024 (DSA)

1. Write a C program for Insertion Sort

Source Code:

/* Surianandhan S
127018060
CSBS 2nd Semester
27-03-2024
Insertion Sort */

#include <stdio.h>

void insertionSort(int arr[], int n)


{
int i, key, j;
for (i = 1; i < n; i++)
{
key = arr[i];
j = i - 1;

while (j >= 0 && arr[j] > key)


{
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}

int main()
{
int size, value;
printf("Enter Number of Elements in an Array: ");
scanf("%d", &size);
int arr[size];
for(int i = 0; i < size; i++)
{
printf("Enter Value: ");
scanf("%d", &value);
arr[i] = value;
}
int n = sizeof(arr) / sizeof(arr[0]);

insertionSort(arr, n);

printf("Sorted Array: \n");


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

return 0;
}

OUTPUT:
Enter Number of Elements in an Array: 5
Enter Value: 5
Enter Value: 4
Enter Value: 9
Enter Value: 8
Enter Value: 3
Sorted array:
34589

Enter Number of Elements in an Array: 4


Enter Value: 5
Enter Value: 8
Enter Value: 3
Enter Value: 7
Sorted array:
3578
2. Write a C program for Merge Sort

Source Code:

/* Surianandhan S
127018060
CSBS 2nd Semester
27-03-2024
Merge Sort */

#include <stdio.h>

void merge(int arr[], int low, int mid, int high)


{
int n1 = mid - low + 1;
int n2 = high - mid;

int left[n1], right[n2];

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


{
left[i] = arr[low + i];
}
for (int j = 0; j < n2; j++)
{
right[j] = arr[mid + 1 + j];
}

int i = 0, j = 0, k = low;
while (i < n1 && j < n2)
{
if (left[i] <= right[j])
{
arr[k] = left[i];
i++;
}
else
{
arr[k] = right[j];
j++;
}
k++;
}

while (i < n1)


{
arr[k] = left[i];
i++;
k++;
}

while (j < n2)


{
arr[k] = right[j];
j++;
k++;
}
}

void mergeSort(int arr[], int low, int high)


{
if (low < high)
{
int mid = low + (high - low) / 2;

mergeSort(arr, low, mid);


mergeSort(arr, mid + 1, high);

merge(arr, low, mid, high);


}
}

int main()
{
int size, value;
printf("Enter Number of Elements in an Array: ");
scanf("%d", &size);
int arr[size];
for(int i = 0; i < size; i++)
{
printf("Enter Value: ");
scanf("%d", &value);
arr[i] = value;
}
int n = sizeof(arr) / sizeof(arr[0]);

mergeSort(arr, 0, n - 1);

printf("Sorted array: \n");


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

return 0;
}

OUTPUT:
Enter Number of Elements in an Array: 5
Enter Value: 9
Enter Value: 4
Enter Value: 5
Enter Value: 8
Enter Value: 3
Sorted array:
34589

Enter Number of Elements in an Array: 4


Enter Value: 9
Enter Value: 1
Enter Value: 5
Enter Value: 7
Sorted array:
1579
C Program 03-04-2024 (DSA)

1. Write a C program for Traversing the Graph in BFS

Source Code:

/* Surianandhan S
127018060
CSBS 2nd Semester
03-04-2024
BFS */

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

#define MAX_VERTICES 100

int queue[MAX_VERTICES];
int front = -1, rear = -1;

int visited[MAX_VERTICES];

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

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

struct Node* createNode(int data)


{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

struct Graph* createGraph(int numVertices)


{
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->numVertices = numVertices;

graph->adjLists = (struct Node**)malloc(numVertices * sizeof(struct Node*));

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


{
graph->adjLists[i] = NULL;
}

return graph;
}

void addEdge(struct Graph* graph, int src, int dest)


{
struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

void enqueue(int value)


{
if (rear == MAX_VERTICES - 1)
{
printf("Queue Overflow\n");
}
else
{
if (front == -1)
{
front = 0;
}
queue[++rear] = value;
}
}

int dequeue()
{
if (front == -1 || front > rear)
{
printf("Queue Underflow\n");
return -1;
}
else
{
return queue[front++];
}
}

void markVisited(int node)


{
visited[node] = 1;
}

int isVisited(int node)


{
return visited[node];
}

void BFS(struct Graph* graph, int startVertex)


{
for (int i = 0; i < graph->numVertices; i++)
{
visited[i] = 0;
}

enqueue(startVertex);
markVisited(startVertex);

while (front <= rear)


{
int currentVertex = dequeue();
printf("%d", currentVertex);

struct Node* temp = graph->adjLists[currentVertex];

while (temp)
{
if (!isVisited(temp->data))
{
enqueue(temp->data);
markVisited(temp->data);
}
temp = temp->next;
}
}
}

int main()
{
int numVertices, numEdges, source;

printf("Enter the Number of Vertices: ");


scanf("%d", &numVertices);

printf("Enter the Number of Edges: ");


scanf("%d", &numEdges);

struct Graph* graph = createGraph(numVertices);

printf("Enter Source Vertex: ");


scanf("%d", &source);

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


{
int src, dest;
printf("Enter Source for Edge %d: ", i + 1);
scanf("%d", &src);
printf("Enter Destination for Edge %d: ", i + 1);
scanf("%d", &dest);
addEdge(graph, src, dest);
}
printf("BFS Traversal from Source %d: \n", source);
BFS(graph, source);
printf("\n");
return 0;
}

OUTPUT:
Enter the Number of Vertices: 4
Enter the Number of Edges: 3
Enter Source Vertex: 1
Enter Source for Edge 1: 1
Enter Destination for Edge 1: 2
Enter Source for Edge 2: 2
Enter Destination for Edge 2: 3
Enter Source for Edge 3: 3
Enter Destination for Edge 3: 4
BFS Traversal from Source 1:
1234
2. Write a C program for Traversing the Graph in DFS

Source Code:

/* Surianandhan S
127018060
CSBS 2nd Semester
03-04-2024
DFS */

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

#define MAX_VERTICES 100

int visited[MAX_VERTICES];

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

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

struct Node* createNode(int data)


{
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}

struct Graph* createGraph(int numVertices)


{
struct Graph* graph = (struct Graph*)malloc(sizeof(struct Graph));
graph->numVertices = numVertices;

graph->adjLists = (struct Node**)malloc(numVertices * sizeof(struct Node*));


for (int i = 0; i < numVertices; ++i)
{
graph->adjLists[i] = NULL;
}

return graph;
}

void addEdge(struct Graph* graph, int src, int dest)


{
struct Node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

newNode = createNode(src);
newNode->next = graph->adjLists[dest];
graph->adjLists[dest] = newNode;
}

void markVisited(int node)


{
visited[node] = 1;
}

void DFSUtil(struct Graph* graph, int vertex)


{
markVisited(vertex);
printf("%d", vertex);

struct Node* temp = graph->adjLists[vertex];

while (temp)
{
if (!visited[temp->data])
{
DFSUtil(graph, temp->data);
}
temp = temp->next;
}
}

void DFS(struct Graph* graph, int startVertex)


{
for (int i = 0; i < graph->numVertices; i++)
{
visited[i] = 0;
}

DFSUtil(graph, startVertex);
}

int main()
{
int numVertices, numEdges, source;

printf("Enter the Number of Vertices: ");


scanf("%d", &numVertices);

printf("Enter the Number of Edges: ");


scanf("%d", &numEdges);

struct Graph* graph = createGraph(numVertices);

printf("Enter Source Vertex: ");


scanf("%d", &source);

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


{
int src, dest;
printf("Enter Source for Edge %d: ", i + 1);
scanf("%d", &src);
printf("Enter Destination for Edge %d: ", i + 1);
scanf("%d", &dest);
addEdge(graph, src, dest);
}

printf("DFS Traversal from Source %d: \n", source);


DFS(graph, source);
printf("\n");
return 0;
}
OUTPUT:
Enter the Number of Vertices: 4
Enter the Number of Edges: 3
Enter Source Vertex: 1
Enter Source for Edge 1: 1
Enter Destination for Edge 1: 2
Enter Source for Edge 2: 2
Enter Destination for Edge 2: 3
Enter Source for Edge 3: 3
Enter Destination for Edge 3: 4
DFS Traversal from Source 1:
1234
C Program 03-04-2024 (DSA)

Write a C program for Operations on AVL Tree

Source Code:

/* Surianandhan S
127018060
CSBS 2nd Semester
03-04-2024
AVL */

1. AVLTREE.c

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

int height(TNODE *t)


{
if (t == NULL)
return 0;
else
{
int hl = height(t->lchild);
int hr = height(t->rchild);
int h = hl >= hr ? hl+1 : hr+1;
return h;
}
}

int getBalanceFactor(TNODE *t)


{
if (t == NULL)
return 0;
else
return height(t->lchild) - height(t->rchild);
}

TNODE* insertnode(TNODE *t, int key)


{
if (t == NULL)
{
TNODE *newnode = (TNODE *) malloc(sizeof(TNODE));
newnode->data = key;
newnode->lchild = NULL;
newnode->rchild = NULL;
return newnode;
}
if (key < t->data)
t->lchild = insertnode(t->lchild, key);
else if (key > t->data)
t->rchild = insertnode(t->rchild, key);
else
{
printf( "Duplicate keys. Can't Insert\n" );
return NULL;
}
int bf = getBalanceFactor(t);
if (bf == 2 && key < t->lchild->data)
return rightRotate(t);
if (bf == -2 && key > t->rchild->data)
return leftRotate(t);

if (bf == 2 && key > t->lchild->data)


{
t->lchild = leftRotate(t->lchild);
return rightRotate(t);
}
if (bf == -2 && key < t->rchild->data)
{
t->rchild = rightRotate(t->rchild);
return leftRotate(t);
}
return t;
}

void search(TNODE *root, int t)


{
int count = 0;
if (root == NULL)
{
printf( "Empty AVL tree.\n");
return;
}
TNODE *temp=root;
while (temp != NULL)
{
count++;
if (temp->data > t)
temp = temp->lchild;
else if (temp->data < t)
temp = temp->rchild;
else
{
printf( "The element is found after %d comparisons.\n", count );
return;
}
}
printf( "The element is not found.\n");
}

TNODE* leftRotate(TNODE *t)


{
printf( "Left Rotate on : %d\n", t->data);
TNODE *y = t->rchild;
t->rchild = y->lchild;
y->lchild = t;
return y;
}

TNODE* rightRotate(TNODE *t)


{
printf( "Right Rotate on : %d\n", t->data);
TNODE *y = t->lchild;
t->lchild = y->rchild;
y->rchild = t;
return y;
}

void preorder(TNODE *temp)


{
if (temp != NULL)
{
printf( "%d ", temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}
void inorder(TNODE *temp)
{
if (temp != NULL)
{
inorder(temp->lchild);
printf( "%d ", temp->data);
inorder(temp->rchild);
}
}
void postorder(TNODE *temp)
{
if (temp != NULL)
{
postorder(temp->lchild);
postorder(temp->rchild);
printf( "%d ", temp->data);
}
}

2. AVL.h

#include <stdio.h>
typedef struct node
{
int data;
struct node *lchild;
struct node *rchild;
}TNODE;

int height(TNODE *t);


int getBalanceFactor(TNODE *t);
TNODE* insertnode(TNODE *t, int key);
void search(TNODE* temp, int t);
TNODE* leftRotate(TNODE *t);
TNODE* rightRotate(TNODE *t);
void preorder(TNODE *temp);
void inorder(TNODE *temp);
void postorder(TNODE *temp);

3. AVLMain.c

#include <stdio.h>
#include "AVLTREE.c"
int main()
{
TNODE *root= NULL;
int d, op;
do
{
printf( "1. Insert Element \n2. Search Element \n3. Traverse\n4. Exit\n");
scanf("%d", &op);
switch (op)
{
case 1: {
printf( "Enter element to insert ");
scanf("%d", &d);
root = insertnode(root, d);
printf( "Preorder : ");
preorder(root);
printf("\nInorder : ");
inorder(root);
printf("\nPostorder : ");
postorder(root);
printf("\n");
break;
}
case 2: {
printf( "Enter element to search ");
scanf("%d", &d);
search(root, d);
break;
}
case 3: {
printf( "Preorder : ");
preorder(root);
printf("\nInorder : ");
inorder(root);
printf( "\nPostorder : ");
postorder(root);
printf("\n");
break;
}
}
}
while (op < 4);
}
OUTPUT:
1. Insert Element
2. Search Element
3. Traverse
4. Exit
1
Enter element to insert 10
Preorder : 10
Inorder : 10
Postorder : 10

1. Insert Element
2. Search Element
3. Traverse
4. Exit
1
Enter element to insert 5
Left Rotate on : 10
Preorder : 5 10
Inorder : 5 10
Postorder : 10 5

1. Insert Element
2. Search Element
3. Traverse
4. Exit
1
Enter element to insert 15
Right Rotate on : 10
Preorder : 5 10 15
Inorder : 5 10 15
Postorder : 15 10 5

1. Insert Element
2. Search Element
3. Traverse
4. Exit
1
Enter element to insert 20
Right Rotate on : 10
Left Rotate on : 15
Preorder : 5 15 10 20
Inorder : 5 10 15 20
Postorder : 10 20 15 5
1. Insert Element
2. Search Element
3. Traverse
4. Exit
2
Enter element to search 15
The element is found after 2 comparisons.

1. Insert Element
2. Search Element
3. Traverse
4. Exit
2
Enter element to search 25
The element is not found.

1. Insert Element
2. Search Element
3. Traverse
4. Exit
4
C Program 03-04-2024 (DSA)

1. Write a C program for Hash Search

Source Code:

/* Surianandhan S
127018060
CSBS 2nd Semester
03-04-2024
Hash Search */

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

#define SIZE 10

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

struct Node* hashTable[SIZE];

void initializeHashTable() {
for (int i = 0; i < SIZE; ++i) {
hashTable[i] = NULL;
}
}

void insert(int data) {


int index = data % SIZE;

struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));


newNode->data = data;
newNode->next = NULL;

if (hashTable[index] == NULL) {
hashTable[index] = newNode;
} else {
struct Node* temp = hashTable[index];
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newNode;
}
}

void search(int data) {


int index = data % SIZE;

struct Node* temp = hashTable[index];

while (temp != NULL) {


if (temp->data == data) {
printf("Data %d found in hash table.\n", data);
return;
}
temp = temp->next;
}

printf("Data %d not found in hash table.\n", data);


}

int main() {
initializeHashTable();

int choice, data;

while (1) {
printf("\n1. Insert\n2. Search\n3. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter data to insert: ");
scanf("%d", &data);
insert(data);
break;
case 2:
printf("Enter data to search: ");
scanf("%d", &data);
search(data);
break;
case 3:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice. Please try again.\n");
}
}

return 0;
}
OUTPUT:
1. Insert
2. Search
3. Exit
Enter your choice: 1
Enter data to insert: 5

1. Insert
2. Search
3. Exit
Enter your choice: 1
Enter data to insert: 15

1. Insert
2. Search
3. Exit
Enter your choice: 1
Enter data to insert: 25

1. Insert
2. Search
3. Exit
Enter your choice: 2
Enter data to search: 15
Data 15 found in hash table.

1. Insert
2. Search
3. Exit
Enter your choice: 2
Enter data to search: 20
Data 20 not found in hash table.

1. Insert
2. Search
3. Exit
Enter your choice: 3
Exiting program.
C Program 10-04-2024 (DSA)

1. Write a C program to Store and Load Non-Linear Data Structure (Graph)

Source Code:

/* Surianandhan S
127018060
CSBS 2nd Semester
10-04-2024
Saving / retrieving non-linear data structure in / from a file */

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

#define MAX_VERTICES 100

struct Edge {
int weight;
struct Vertex* destination;
struct Edge* next;
};

struct Vertex {
char name[50];
struct Edge* edge;
};

struct Graph {
struct Vertex vertices[MAX_VERTICES];
int numVertices;
};

void storeGraph(struct Graph *g, char filename[]) {


FILE *file = fopen(filename, "w");
if (file == NULL) {
printf("Error opening file.\n");
return;
}

fprintf(file, "%d\n", g->numVertices);


for (int i = 0; i < g->numVertices; ++i) {
fprintf(file, "%s\n", g->vertices[i].name);
struct Edge *currentEdge = g->vertices[i].edge;
while (currentEdge != NULL) {
fprintf(file, "%d %s\n", currentEdge->weight, currentEdge->destination->name);
currentEdge = currentEdge->next;
}
fprintf(file, "NULL\n");
}

fclose(file);
}

void loadGraph(struct Graph *g, char filename[]) {


FILE *file = fopen(filename, "r");
if (file == NULL) {
printf("Error opening file.\n");
return;
}

fscanf(file, "%d", &g->numVertices);


for (int i = 0; i < g->numVertices; ++i) {
fscanf(file, "%s", g->vertices[i].name);
g->vertices[i].edge = NULL;
}

for (int i = 0; i < g->numVertices; ++i) {


struct Vertex *currentVertex = &g->vertices[i];
while (1) {
int weight;
char destinationName[50];
fscanf(file, "%d %s", &weight, destinationName);
if (strcmp(destinationName, "NULL") == 0) break;

struct Edge *newEdge = (struct Edge *)malloc(sizeof(struct Edge));


newEdge->weight = weight;
newEdge->next = NULL;

for (int j = 0; j < g->numVertices; ++j) {


if (strcmp(g->vertices[j].name, destinationName) == 0) {
newEdge->destination = &g->vertices[j];
break;
}
}
if (currentVertex->edge == NULL) {
currentVertex->edge = newEdge;
} else {
struct Edge *temp = currentVertex->edge;
while (temp->next != NULL) {
temp = temp->next;
}
temp->next = newEdge;
}
}
}
fclose(file);
}

void displayGraph(struct Graph *g) {


printf("Number of vertices: %d\n", g->numVertices);
for (int i = 0; i < g->numVertices; ++i) {
printf("%s\n", g->vertices[i].name);
struct Edge *currentEdge = g->vertices[i].edge;
while (currentEdge != NULL) {
printf("→ Weight: %d, Destination: %s\n", currentEdge->weight,
currentEdge->destination->name);
currentEdge = currentEdge->next;
}
}
}

int main() {
struct Graph g;
char filename[100];

printf("Enter file name to store graph details: ");


scanf("%s", filename);
storeGraph(&g, filename);

printf("\nEnter file name to load graph details: ");


scanf("%s", filename);
loadGraph(&g, filename);

printf("\nGraph Details:\n");
displayGraph(&g);

return 0;
}
OUTPUT:
Enter file name to store graph details: graph.txt

Enter file name to load graph details: graph.txt

Graph Details:
Number of vertices: 3
A
→ Weight: 10, Destination: B
→ Weight: 20, Destination: C
B
→ Weight: 15, Destination: C
C

Enter file name to store graph details: mygraph.txt

Enter file name to load graph details: mygraph.txt

Graph Details:
Number of vertices: 4
A
→ Weight: 5, Destination: B
→ Weight: 10, Destination: C
B
→ Weight: 15, Destination: D
C
→ Weight: 20, Destination: D
D

You might also like