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

dsa llab

The document outlines a laboratory course on Data Structures and Algorithms using C at New Horizon College of Engineering, detailing various experiments and programming tasks. Each experiment includes aims, input/output formats, and example code, such as converting infix expressions to postfix and managing a doubly linked list. The document serves as a comprehensive guide for students to complete their programming assignments and understand fundamental data structures.

Uploaded by

S.Y Suprabhath
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)
4 views

dsa llab

The document outlines a laboratory course on Data Structures and Algorithms using C at New Horizon College of Engineering, detailing various experiments and programming tasks. Each experiment includes aims, input/output formats, and example code, such as converting infix expressions to postfix and managing a doubly linked list. The document serves as a comprehensive guide for students to complete their programming assignments and understand fundamental data structures.

Uploaded by

S.Y Suprabhath
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/ 60

: Data Structures And Algorithms Laboratory using

C - 22AIL32 - 2024

New Horizon College of Engineering

Submitted By

Student Name SIDDAVARAM SUPRABHATH YASHASWI

Roll No. 1NH23EC155

Programme

Semester

Section

Session/Batch

Submitted To

Faculty Name

1
S.No. Experiment Aim of Experiment Signature/Date Grade
Date

1 Sunday, 5th Convert an Infix Expression to


Jan 2025 Postfix and Evaluate it.

2 Tuesday, Program to Delete an element


22nd Oct at End from Doubly Linked List
2024

3 Sunday, 5th Program to insert into BST and


Jan 2025 traversal using In-order, Pre-
order and Post-order

4 Sunday, 5th Building max heap


Jan 2025

5 Sunday, 5th Activity Selection Problem


Jan 2025

6 Tuesday, 5th Managing print job requests


Nov 2024 using circular queue

7 Sunday, 5th Music management system


Jan 2025 using Single Linked List

8 Sunday, 5th Course Scheduling with


Jan 2025 Prerequisites: Topological Sort
Implementation

9 Tuesday, Shortest connection between


10th Dec two users in a network
2024

10 Sunday, 5th Single source shortest path


Jan 2025 from one bus stop to others

11 Sunday, 5th Unique identifier generation


Jan 2025 using hashing.

12 Sunday, 5th Huffman Code


Jan 2025

2
New Horizon College of Engineering

Program - 1
Date of performance: 5th Jan 2025

Aim:
Write a C program that uses a stack to evaluate an infix expression and convert it to a postfix expression.

Note: Only single-digit positive integers and +, -, *, /, % operators are allowed

Input Format
• A string representing the infix mathematical expression

Output Format
• The first line of output represents the converted postfix notation of the infix expression.
• The second line of output represents the result of evaluating the postfix expression.

EvaluateConverted.c

SIDDAVARAM SUPRABHATH YASHASWI 3 1NH23EC155


New Horizon College of Engineering

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

#define MAX_SIZE 100


char stack[MAX_SIZE];
int top=-1;
void push(char item)
{
if(top>=MAX_SIZE-1)
printf("Stack Overflow\n");
else{
++top;
stack[top]=item;
}
}
char pop()
{
if(top==-1)
{
printf("Stack Underflow\n");
return 0;
}
else{
return stack[top--];
}
}
int precedence(char symbol)
{
switch(symbol)
{
case'+':
case'-': return 1;
case'*':
case'/':
case'%': return 2;
case'^':return 3;
default: return 0;
}
}
int isOperator(char symbol)
{
if(symbol=='+'||symbol=='-

SIDDAVARAM SUPRABHATH YASHASWI 4 1NH23EC155


New Horizon College of Engineering

'||symbol=='*'||symbol=='/'||symbol=='%'||symbol=='^')
return 1;
else
return 0;
}
// Function to convert infix expression to postfix notation
void infixToPostfix(char infix[],char postfix[])
{
int i=0,j=0;
char item,temp;
while(infix[i]!='\0'&&infix[i]!='\n')
{
item=infix[i];
if((item>='A'&&item<='Z')||
(item>='a'&&item<='z')||isdigit(item))
{
postfix[j]=item;
j++;
}
else if(item=='(')
{
push(item);
}
else if(item==')')
{
while(top!=-1&&(temp=pop())!='(')
{
postfix[j]=temp;
j++;
}
}
else if(isOperator(item))
{
while(top!=-1&&precedence(stack[top])>=precedence(item))
{
postfix[j]=pop();
j++;
}

push(item);
}
i++;
}

SIDDAVARAM SUPRABHATH YASHASWI 5 1NH23EC155


New Horizon College of Engineering

while(top!=-1)
{
postfix[j]=pop();
j++;
}
postfix[j]='\0';
}
// Function to evaluate a postfix expression
int evaluatePostfixExpression(char postfix[]) {
int stack[MAX_SIZE] ,i=0,j,top=-1,operand1,operand2,result;
char item;
while(postfix[i]!='\0')
{
item=postfix[i];
if(isalnum(item))
{
top++;
stack[top]=(item-'0');
}
else if(isOperator(item))
{
operand2=stack[top];
top--;
operand1=stack[top];
top--;
switch(item)
{
case
'+':result=operand1+operand2;
break;
case '-':result=operand1-operand2;
break;
case
'*':result=operand1*operand2;
break;
case
'/':result=operand1/operand2;
break;
case
'%':result=operand1%operand2;
break;
case '^':result=1;
for(j=0;j<=operand2;j++)

SIDDAVARAM SUPRABHATH YASHASWI 6 1NH23EC155


New Horizon College of Engineering

result=result*operand1;
break;
}
top++;
stack[top]=result;
}
i++;
}
return stack[top];

int main() {
char infixExpression[MAX_SIZE];
char postfixExpression[MAX_SIZE];

printf("Infix expression: ");


scanf("%s", infixExpression);

infixToPostfix(infixExpression, postfixExpression);

printf("Postfix expression: %s\n", postfixExpression);

int result = evaluatePostfixExpression(postfixExpression);

printf("Result: %d\n", result);

return 0;
}

Output:

Test case - 1

User Output
Infix expression:
2+3*4
Postfix expression: 234*+
Result: 14

Test case - 2

User Output
Infix expression:

SIDDAVARAM SUPRABHATH YASHASWI 7 1NH23EC155


New Horizon College of Engineering

8%3+6*(2-1)
Postfix expression: 83%621-*+
Result: 8

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 8 1NH23EC155


New Horizon College of Engineering

Program - 2
Date of performance: 22nd Oct 2024
Aim:
Write a C program to delete a node from the end in a doubly linked list

Input Format
Menu Options: The user is prompted with a menu of options:
1. Insert at end
2. Delete at end
3. Traverse the list
4. Exit
Element Input: When choosing to insert at the end, the user will provide a value to be inserted into the DLL.

Output Format
5. Insertion: After inserting an element, the menu will be displayed again.
6. Deletion: After deleting an element, the deleted element's value will be displayed in the format "The
deleted element from DLL : <element>", followed by the menu.
7. Traversal: When traversing, the current elements of the DLL will be displayed in a specific format like "The
elements in DLL are : <element1> <--> <element2> <-->.... <elementn>", followed by the menu.
8. Exit: The program will terminate.

DoubleLL6.c

SIDDAVARAM SUPRABHATH YASHASWI 9 1NH23EC155


New Horizon College of Engineering

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

#include "DelAtEndingInDLL.c"

void main() {
NODE first = NULL;
int x, op;
while(1) {
printf("1.Insert At End 2.Delete at End 3.Traverse the
List 4.Exit\n");
printf("Enter your option : ");
scanf("%d", &op);
switch(op) {
case 1: printf("Enter an element : ");
scanf("%d", &x);
first =
insertAtEndInDLL(first, x);
break;
case 2: if (first == NULL) {
printf("Double Linked
List is empty so deletion is not possible\n");
} else {
first =
deleteAtEndInDLL(first);
}
break;
case 3: if (first == NULL) {
printf("Double Linked
List is empty\n");
} else {
printf("The elements
in DLL are : ");

traverseListInDLL(first);
}
break;
case 4: exit(0);
}
}
}

DelAtEndingInDLL.c

SIDDAVARAM SUPRABHATH YASHASWI 10 1NH23EC155


New Horizon College of Engineering

struct node {
int data;
struct node *prev;
struct node *next;
};
typedef struct node * NODE;

NODE createNodeInDLL() {
NODE temp;
temp = (NODE)malloc(sizeof(struct node));
temp->prev = NULL;
temp->next = NULL;
return temp;
}

NODE insertAtEndInDLL(NODE first, int x) {


NODE temp, lastNode = first;
temp = createNodeInDLL();
temp -> data = x;
if (first == NULL) {
first = temp;
} else {
while (lastNode -> next != NULL) {
lastNode = lastNode -> next;
}
lastNode -> next = temp;
temp -> prev = lastNode;
}
return first;
}

NODE deleteAtEndInDLL(NODE head) {


NODE temp,lastNode=head;
if(head==NULL){
printf("deletion not possible");
}
else{
if(lastNode ->next==NULL){
head=NULL;
}
else{
while(lastNode -> next!=NULL){
temp=lastNode;

SIDDAVARAM SUPRABHATH YASHASWI 11 1NH23EC155


New Horizon College of Engineering

lastNode=lastNode ->next;
}
temp ->next=NULL;
}
printf("The deleted element from DLL : %d\n",lastNode
->data);
}
free(lastNode);
return head;
}

void traverseListInDLL(NODE first) {


NODE lastNode = first;
while (lastNode != NULL) {
printf("%d <--> ", lastNode -> data);
lastNode = lastNode -> next;
}
printf("NULL\n");
}

Output:

Test case - 1

User Output
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
2
Double Linked List is empty so deletion is not possible
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
3
Double Linked List is empty
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
1
Enter an element :
22
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
1
Enter an element :
44

SIDDAVARAM SUPRABHATH YASHASWI 12 1NH23EC155


New Horizon College of Engineering
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
3
The elements in DLL are : 22 <--> 44 <--> NULL
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
2
The deleted element from DLL : 44
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
2
The deleted element from DLL : 22
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
2
Double Linked List is empty so deletion is not possible
1.Insert At End 2.Delete at End 3.Traverse the List 4.Exit
Enter your option :
4

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 13 1NH23EC155


New Horizon College of Engineering

Program - 3
Date of performance: 5th Jan 2025
Aim:
Write a program to create a binary search tree of integers and perform the following operations using linked list.
9. Insert a node
10. In-order traversal
11. Pre-order traversal
12. Post-order traversal

Note: Write the code in InsertAndTraversals.c file.

BinarySearchTree.c

SIDDAVARAM SUPRABHATH YASHASWI 14 1NH23EC155


New Horizon College of Engineering

#include<stdio.h>
#include<stdlib.h>
#include "InsertAndTraversals.c"

void main() {
int x, op;
BSTNODE root = NULL;
while(1) {
printf("1.Insert 2.Inorder Traversal 3.Preorder
Traversal 4.Postorder Traversal 5.Exit\n");
printf("Enter your option : ");
scanf("%d", &op);
switch(op) {
case 1:
printf("Enter an element to be
inserted : ");
scanf("%d", &x);
root = insertNodeInBST(root,x);
break;
case 2:
if(root == NULL) {
printf("Binary Search Tree is
empty.\n");
}
else {
printf("Elements of the BST
(in-order traversal): ");
inorderInBST(root);
printf("\n");
}
break;
case 3:
if(root == NULL) {
printf("Binary Search Tree is
empty.\n");
}
else {
printf("Elements of the BST
(pre-order traversal): ");
preorderInBST(root);
printf("\n");
}
break;

SIDDAVARAM SUPRABHATH YASHASWI 15 1NH23EC155


New Horizon College of Engineering

case 4:
if(root == NULL) {
printf("Binary Search Tree is
empty.\n");
}
else {
printf("Elements of the BST
(post-order traversal): ");
postorderInBST(root);
printf("\n");
}
break;
case 5:
exit(0);
}
}
}

InsertAndTraversals.c

SIDDAVARAM SUPRABHATH YASHASWI 16 1NH23EC155


New Horizon College of Engineering

struct node {
int data;
struct node *left, *right;
};

typedef struct node *BSTNODE;

BSTNODE newNodeInBST(int item) {


BSTNODE temp = (BSTNODE)malloc(sizeof(struct node));
temp->data = item;
temp->left = temp->right = NULL;
return temp;
}

BSTNODE insertNodeInBST(BSTNODE node, int ele) {


if(node==NULL){
printf("Successfully inserted.\n");
return newNodeInBST(ele);
}
if(ele<node->data)
node->left=insertNodeInBST(node->left,ele);
else if(ele>node->data)
node->right=insertNodeInBST(node->right,ele);
else
printf("Element already exists in BST.\n");

return node;
}

void inorderInBST(BSTNODE root) {


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

void preorderInBST(BSTNODE root) {


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

SIDDAVARAM SUPRABHATH YASHASWI 17 1NH23EC155


New Horizon College of Engineering

preorderInBST(root->left);
preorderInBST(root->right);
}
}

void postorderInBST(BSTNODE root) {


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

Output:

Test case - 1

User Output
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
54
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
28
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
62
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
2
Elements of the BST (in-order traversal): 28 54 62
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
3

SIDDAVARAM SUPRABHATH YASHASWI 18 1NH23EC155


New Horizon College of Engineering
Elements of the BST (pre-order traversal): 54 28 62
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
4
Elements of the BST (post-order traversal): 28 62 54
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
5

Test case - 2

User Output
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
100
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
20
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
200
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
10
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
30
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit

SIDDAVARAM SUPRABHATH YASHASWI 19 1NH23EC155


New Horizon College of Engineering
Enter your option :
1
Enter an element to be inserted :
150
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
300
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
2
Elements of the BST (in-order traversal): 10 20 30 100 150 200 300
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
3
Elements of the BST (pre-order traversal): 100 20 10 30 200 150 300
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
4
Elements of the BST (post-order traversal): 10 30 20 150 300 200 100
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
5

Test case - 3

User Output
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
12
Successfully inserted.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
1
Enter an element to be inserted :
12
Element already exists in BST.
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit

SIDDAVARAM SUPRABHATH YASHASWI 20 1NH23EC155


New Horizon College of Engineering
Enter your option :
2
Elements of the BST (in-order traversal): 12
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
3
Elements of the BST (pre-order traversal): 12
1.Insert 2.Inorder Traversal 3.Preorder Traversal 4.Postorder Traversal 5.Exit
Enter your option :
5

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 21 1NH23EC155


New Horizon College of Engineering

Program - 4
Date of performance: 5th Jan 2025
Aim:
Develop a C program to create a Max heap using a given set of integers.

Input Format:
• First Line: An integer n indicates the number of elements in the array.
• Second Line: n space-separated integers representing the elements of the array.

Output Format:
• First Line: A print of the original array elements in the order they were entered which are space-separated.
• Second Line: A print of the array elements after converting it into a max heap which are space-separated.

Note: The partial code has been provided to you in the editor, you are required to fill in the missing parts.

maxHeapCreation.c

SIDDAVARAM SUPRABHATH YASHASWI 22 1NH23EC155


New Horizon College of Engineering

#include <stdio.h>
// Function to swap two elements
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
// Function to heapify a subtree rooted at index i
void heapify(int a[],int n,int i)
{
int largest=i;
int left=2*i+1;
int right=2*i+2;
if(left<n &&a[left]>a[largest])
largest=left;
if(right<n &&a[right]>a[largest])
largest=right;
if(largest!=i)
{
swap(&a[i],&a[largest]);
heapify(a,n,largest);
}
}
// Function to build a max heap from a given array
void buildMaxHeap(int a[],int n)
{
for(int i=n/2-1;i>=0;i--){
heapify(a,n,i);
}
}
// Function to print the array
void printArray(int arr[], int size) {
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
int main() {
int n;
// Take the number of elements in the array from the user
//printf("Enter the number of elements in the array: ");
scanf("%d", &n);
// Declare an array of size n

SIDDAVARAM SUPRABHATH YASHASWI 23 1NH23EC155


New Horizon College of Engineering

int arr[n];
// Take array elements from the user
//printf("Enter %d elements for the array:\n", n);
for (int i = 0; i < n; i++) {
scanf("%d", &arr[i]);
}
//printf("Original array:\n");
printArray(arr, n);
// Build max heap
buildMaxHeap(arr, n);
//printf("Max Heap:\n");
printArray(arr, n);
return 0;
}

Output:

Test case - 1

User Output
5
31425
3 1 4 2 5
5 3 4 2 1

Test case - 2

User Output
3
465
4 6 5
6 4 5

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 24 1NH23EC155


New Horizon College of Engineering

Program - 5
Date of performance: 5th Jan 2025

Aim:
Write a C program to implement Greedy algorithm using Activity Selection Problem.

Note:
• The activities are numbered from 0 to n-1, where n is the number of activities.
• Sort the activities according to their finishing time.
• If the activity has start time greater than or equal to the finish time of previously selected activity, then
select it.

ASP.c

SIDDAVARAM SUPRABHATH YASHASWI 25 1NH23EC155


New Horizon College of Engineering

#include<stdio.h>
void sortActivities(int n,int start[],int finish[]){
for(int i=0;i<n-1;i++){
for(int j=i+1;j<n;j++){
if(finish[i]>finish[j]){
int temp=finish[i];
finish[i]=finish[j];
finish[j]=temp;
temp=start[i];
start[i]=start[j];
start[j]=temp;
}
}
}
}
void activitySelection(int n,int start[],int finish[]){
sortActivities(n,start,finish);
printf("The following activities are selected: \n");
int i=0;
printf("%d %d\n",start[i],finish[i]);
for(int j=1;j<n;j++){
if(start[j]>=finish[i]){
printf("%d %d\n",start[j],finish[j]);
i=j;
}
}
}
int main(){
int n;
printf("Enter the number of activities: ");
scanf("%d",&n);
int start[n],finish[n];
printf("Enter the start and finish times of each activity:
\n");
for(int i=0;i<n;i++){
scanf("%d %d",&start[i],&finish[i]);
}

activitySelection(n,start,finish);
return 0;
}

Output:

SIDDAVARAM SUPRABHATH YASHASWI 26 1NH23EC155


New Horizon College of Engineering

Test case - 1

User Output
Enter the number of activities:
4
Enter the start and finish times of each activity:
1 10
96
85
63
The following activities are selected:
6 3
8 5
9 6

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 27 1NH23EC155


New Horizon College of Engineering

Program - 6
Date of performance: 5th Nov 2024

Aim:
Implement a program using a circular queue to manage print job requests in a printer job scheduling system. The
program should be able to add new print jobs to the circular queue, process and print them, and handle the
circular queue's operations efficiently.

Input Format:
Menu Selection:
Users choose an option from the menu. The available options are:
13. Add Print Job
14. Process Print Job
15. Display Print Jobs
16. Exit
Add Print Job (Option 1):
• First Line : Integer value representing the unique identifier for the print job.
• Second Line : A string representing the description of the print job. Input should be a single line of text.
Process Print Job (Option 2):
• No additional input is required.
Display Print Jobs (Option 3):
• No additional input is required.

Output Format:
After Adding a Print Job:
• Confirmation message indicating that the job has been successfully added to the queue in the format:
"Added Job ID [jobID] to the queue"
After Processing a Print Job:
• Information about the job that has been processed (i.e., removed from the queue) and displays message in
format: "Processing Job ID [jobID]: [description]"
Displaying Print Jobs:
• List of all current print jobs in the queue, showing the Job ID and Description for each in the format "
<JobID>, <description>"
Error or Special Cases:
• Queue Full: If the queue is full when attempting to add a new job, display message in format: Queue is
full
• Queue Empty: If the queue is empty when attempting to process a job or display jobs, display message in
format: Queue is empty
• Invalid Choice: If the user inputs an option not present in the menu, display message in format: Invalid
choice

printJobRequests.c

SIDDAVARAM SUPRABHATH YASHASWI 28 1NH23EC155


New Horizon College of Engineering

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

#define MAX_QUEUE_SIZE 5

// Define a structure for the print job


typedef struct {
int jobID;
char description[100];
} PrintJob;

// Define a structure for the circular queue


typedef struct {
PrintJob queue[MAX_QUEUE_SIZE];
int front;
int rear;
int size;

} CircularQueue;

// Function to initialize the circular queue


void initQueue(CircularQueue *q) {
q->front=0;
q->rear=-1;
q->size=0;

int isEmpty(CircularQueue *q) {


return q->size==0;

int isFull(CircularQueue *q) {


return q->size==MAX_QUEUE_SIZE;

void enqueue(CircularQueue *q, PrintJob job) {


if(isFull(q)){
printf("queue is full");
return;

SIDDAVARAM SUPRABHATH YASHASWI 29 1NH23EC155


New Horizon College of Engineering

}
q->rear=(q->rear+1)%MAX_QUEUE_SIZE;
q->queue[q->rear]=job;
q->size++;
printf("Added Job ID %d to the queue\n",job.jobID);
}

// Function to remove and return a print job from the circular queue
PrintJob dequeue(CircularQueue *q) {
PrintJob job={0,""};
if(isEmpty(q)){
printf("Queue is empty\n");
return job;
}
job=q->queue[q->front];
q->front=(q->front+1)%MAX_QUEUE_SIZE;
q->size--;
return job;

// Function to display the jobs in the queue


void displayQueue(CircularQueue *q) {
if(isEmpty(q)){
printf("Queue is empty\n");
return;
}
int i=q->front;
int count=q->size;
while(count>0){
printf("%d, %s\n",q->queue[i].jobID,q-
>queue[i].description);
i=(i+1)%MAX_QUEUE_SIZE;
count--;
}

int main() {
CircularQueue queue;
initQueue(&queue);

SIDDAVARAM SUPRABHATH YASHASWI 30 1NH23EC155


New Horizon College of Engineering

int choice;
PrintJob job;

while (1) {
printf("Printer Job Scheduling System\n");
printf("1. Add Print Job\n");
printf("2. Process Print Job\n");
printf("3. Display Print Jobs\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // to consume the newline character left by scanf

switch (choice) {
case 1:
if (isFull(&queue)) {
printf("Queue is full\n");
} else {

scanf("%d", &job.jobID);
getchar(); // to consume the newline character
left by scanf
fgets(job.description, 100, stdin);
job.description[strcspn(job.description, "\n")] =
'\0'; // Remove trailing newline
enqueue(&queue, job);
}
break;
case 2:
job = dequeue(&queue);
if (!isEmpty(&queue)) {
printf("Processing Job ID %d: %s\n", job.jobID,
job.description);
}
break;
case 3:
displayQueue(&queue);
break;
case 4:
exit(0);
default:
printf("Invalid choice\n");

SIDDAVARAM SUPRABHATH YASHASWI 31 1NH23EC155


New Horizon College of Engineering

}
}

return 0;
}

Output:

Test case - 1

User Output
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs
4. Exit
Enter your choice:
1
23
abc
Added Job ID 23 to the queue
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs
4. Exit
Enter your choice:
24
Invalid choice
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs
4. Exit
Enter your choice:
4

Test case - 2

User Output
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs

SIDDAVARAM SUPRABHATH YASHASWI 32 1NH23EC155


New Horizon College of Engineering
4. Exit
Enter your choice:
1
24
xyz
Added Job ID 24 to the queue
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs
4. Exit
Enter your choice:
1
25
abc
Added Job ID 25 to the queue
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs
4. Exit
Enter your choice:
2
Processing Job ID 24: xyz
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs
4. Exit
Enter your choice:
3
25, abc
Printer Job Scheduling System
1. Add Print Job
2. Process Print Job
3. Display Print Jobs
4. Exit
Enter your choice:
4

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 33 1NH23EC155


New Horizon College of Engineering

Program - 7
Date of performance: 5th Jan 2025
Aim:
Implement a program that employs a singly linked list to manage music playlists within a music management
system. The program should enable users to insert new songs at specific positions in the playlist, remove songs if
desired, and facilitate navigation through the playlist in the forward direction.

Input Format:
Menu Selection:
Users will be prompted to select an option from the menu with the following choices:
17. Insert New Song
18. Remove Song
19. Display Playlist
20. Exit
Insert New Song (Option 1):
• First Line: String input representing the title of the song.
• Second Line: String input representing the artist of the song.
• Third Line: Integer indicating where the song should be inserted in the playlist (0 for start or a specific
position).
Remove Song (Option 2):
• First Line: String input representing the title of the song to be removed.
Display Playlist (Option 3):
• No additional input required.
Exit (Option 4):
• No additional input required.

Output Format:
After Inserting a New Song:
• Confirmation message indicating that the song has been added to the playlist is displayed in the format:
Inserted song: [title] by [artist] at position [position]
After Removing a Song:
• Confirmation message indicating that the song has been removed from the playlist in the format:
Removed song: [title] or that the song was not found.
Displaying Playlist:
• List of all current songs in the playlist, showing their titles and artists in the format: Title: [title] Artist:
[artist] which are space-separated
Error or Special Cases:
• Position Out of Range: When trying to insert a song at a position beyond the current length of the playlist
it should display message in the format: Position out of range
• Song Not Found: When trying to remove a song that does not exist in the playlistit should display
message in the format: Song not found
• Invalid Choice: When a user enters an option not present in the menuit should display message in the
format: Invalid choice

sllOperations.c

SIDDAVARAM SUPRABHATH YASHASWI 34 1NH23EC155


New Horizon College of Engineering

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

// Define a structure for a song node


typedef struct Song {
char title[100];
char artist[100];
struct Song* next;
} Song;

// Function to create a new song node


Song* createSong(const char* title, const char* artist) {
Song* newnode = (Song*)malloc(sizeof(Song));
if(newnode==NULL){
printf("Memory allocation failed\n");
exit(1);
}
strcpy(newnode->title, title);
strcpy(newnode->artist, artist);
newnode->next=NULL;
return newnode;
}

// Function to insert a song at a specific position


void insertSong(Song** head, const char* title, const char* artist,
int position) {
Song *temp,*prev,*newnode;
int i=0;
newnode=createSong(title,artist);
if(position == 0)
{
newnode->next = *head;
*head = newnode;
}
else{
temp=*head;
prev=NULL;
temp=*head;
while(temp!=NULL&&i<position)
{
prev=temp;
temp=temp->next;

SIDDAVARAM SUPRABHATH YASHASWI 35 1NH23EC155


New Horizon College of Engineering

i++;
}
if(i==position){
prev->next=newnode;
newnode->next=temp;
}
else {
printf("Invalid position\n");
free(newnode);
}
}
}

// Function to remove a song from the playlist


void removeSong(Song** head, const char* title) {
Song *temp,*prev;
temp=*head;
prev=NULL;
while(temp!=NULL)
{
if(strcmp(temp->title,title)==0)
{
if(prev!=NULL)
prev->next=temp->next;
else
*head=temp->next;
printf("Removed song: %s\n",temp->title);
free(temp);
return;
}
prev=temp;
temp=temp->next;
}
printf("Song not found\n");

// Function to display the playlist


void displayPlaylist(Song* head) {
Song *temp=head;
if(temp==NULL){
printf("Playlist is empty\n");
return;

SIDDAVARAM SUPRABHATH YASHASWI 36 1NH23EC155


New Horizon College of Engineering

}
while(temp!=NULL){
printf("%s %s\n",temp->title,temp->artist);
temp=temp->next;
}
}

// Main function
int main() {
Song* playlist = NULL;
int choice, position;
char title[100], artist[100];

while (1) {
printf("Music Playlist Management System\n");
printf("1. Insert New Song\n");
printf("2. Remove Song\n");
printf("3. Display Playlist\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // Consume newline character

switch (choice) {
case 1:
//printf("Enter song title: ");
fgets(title, 100, stdin);
title[strcspn(title, "\n")] = '\0'; // Remove trailing
newline

//printf("Enter song artist: ");


fgets(artist, 100, stdin);
artist[strcspn(artist, "\n")] = '\0'; // Remove
trailing newline

//printf("Enter position to insert the song (0 for


start): ");
scanf("%d", &position);
getchar(); // Consume newline character

insertSong(&playlist, title, artist, position);


break;

SIDDAVARAM SUPRABHATH YASHASWI 37 1NH23EC155


New Horizon College of Engineering

case 2:
//printf("Enter the title of the song to remove: ");
fgets(title, 100, stdin);
title[strcspn(title, "\n")] = '\0'; // Remove trailing
newline

removeSong(&playlist, title);
break;

case 3:
displayPlaylist(playlist);
break;

case 4:
// Free the entire playlist before exiting
while (playlist != NULL) {
Song* temp = playlist;
playlist = playlist->next;
free(temp);
}
exit(0);

default:
printf("Invalid choice\n");
}
}

return 0;
}

Output:

Test case - 1

User Output
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
1
August
Taylor Swift

SIDDAVARAM SUPRABHATH YASHASWI 38 1NH23EC155


New Horizon College of Engineering

0
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
3
August Taylor Swift
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
4

Test case - 2

User Output
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
1
LoveStory
Taylor Swift
0
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
1
Hello
Adele
1
Music Playlist Management System
1. Insert New Song
2. Remove Song

SIDDAVARAM SUPRABHATH YASHASWI 39 1NH23EC155


New Horizon College of Engineering
3. Display Playlist
4. Exit
Enter your choice:
2
LoveStory
Removed song: LoveStory
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
3
Hello Adele
Music Playlist Management System
1. Insert New Song
2. Remove Song
3. Display Playlist
4. Exit
Enter your choice:
4

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 40 1NH23EC155


New Horizon College of Engineering

Program - 8
Date of performance: 5th Jan 2025

Aim:
In a university, students need to plan their course schedules based on prerequisites. Develop a program using
Topological Sort that helps students determine the correct order to take their courses, ensuring all prerequisite
courses are completed before enrolling in advanced ones.

Input Format
• First Line: An integer representing the total number of courses.
• Second Line: An integer representing the number of prerequisite pairs.
• Third Line: Pairs of integers where the first integer is a prerequisite for the second integer. Each line
contains two integers, u and v, separated by a space, where u must be completed before v.

Output Format
• A space-separated list of course numbers representing a valid order of courses where all prerequisites are
completed before advanced courses. If no valid order is possible due to a cycle in the graph, an
appropriate message is displayed in the format "Cycle present so topological sort is not possible".

topologicalSort.c

SIDDAVARAM SUPRABHATH YASHASWI 41 1NH23EC155


New Horizon College of Engineering

#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define MAX 100
int adj[MAX][MAX];
bool visited[MAX];
int stack[MAX];
int top=-1;
void addEdge(int u,int v){
adj[u][v]=1;
}
void dfs(int node,int n){
visited[node]=true;
for(int i=0;i<n;i++){
if(adj[node][i]==1&&!visited[i]){
dfs(i,n);
}
}
stack[++top]=node;
}
bool hasCycleUtil(int node,bool* recursionStack,int n){
if(!visited[node]){
visited[node]=true;
recursionStack[node]=true;
for(int i=0;i<n;i++){
if(adj[node][i]==1){
if(!visited[i]&&hasCycleUtil(i,recursionStack,n)){
return true;
}
else if(recursionStack[i]){
return true;
}
}
}
}
recursionStack[node]=false;
return false;
}
bool hasCycle(int n){
bool recursionStack[MAX]={false};
for(int i=0;i<n;i++){
if(hasCycleUtil(i,recursionStack,n)){
return true;

SIDDAVARAM SUPRABHATH YASHASWI 42 1NH23EC155


New Horizon College of Engineering

}
}
return false;
}
void topologicalSort(int n){
for(int i=0;i<n;i++){
visited[i]=false;
}
for(int i=0;i<n;i++){
if(!visited[i]){
dfs(i,n);
}
}
while(top!=-1){
printf("%d ",stack[top--]);
}
}
int main(){
int n,m;
scanf("%d %d",&n,&m);
for(int i=0;i<n;i++){
for(int j=0;j<n;j++){
adj[i][j]=0;
}
}
for(int i=0;i<m;i++){
int u,v;
scanf("%d %d",&u,&v);
addEdge(u,v);
}
for(int i=0;i<n;i++){
visited[i]=false;
}
if(hasCycle(n)){
printf("Cycle present so topological sort is not possible\n");
}
else{
printf("");
topologicalSort(n);
printf("\n");
}
return 0;
}

SIDDAVARAM SUPRABHATH YASHASWI 43 1NH23EC155


New Horizon College of Engineering

Output:

Test case - 1

User Output
4
3
01
12
23
0 1 2 3

Test case - 2

User Output
3
3
01
12
20
Cycle present so topological sort is not possible

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 44 1NH23EC155


New Horizon College of Engineering

Program - 9
Date of performance: 10th Dec 2024

Aim:
Implement a program using BFS to manage a social network where each user is a node, and friendships between
users are edges. Find the shortest connection path between any two users in the network.

Input Format:
• First Line: The total number of users in the network. This will define the number of nodes in the graph.
• Second Line: The number of undirected friendship connections n between users. Each friendship is
represented by a pair of integers.
• Next n lines: Each line contains two integers representing a friendship between two users. The first integer
is the user ID of one user, and the second integer is the user ID of the friend.
• Next Line: Two space-separated integers representing the start and end user IDs between which you want
to find the shortest path.

Output Format:
• First Line: The length of the shortest path between the start and end user.
• Second Line: The sequence of user IDs that constitutes the shortest path from the start user to the end
user. Each user ID should be displayed in the order of the path.

shortestDistance.c

SIDDAVARAM SUPRABHATH YASHASWI 45 1NH23EC155


New Horizon College of Engineering

#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
#define MAX 100
typedef struct{
int adj[MAX][MAX];
int num;
}graph;
void initial(graph *g,int num){
g->num=num;
for(int i=0;i<num;i++){
for(int j=0;j<num;j++){
g->adj[i][j]=0;
}
}
}
void add(graph *g,int u,int v){
g->adj[u][v]=1;
g->adj[v][u]=1;
}
void find(graph *g,int start,int end)
{
int queue[MAX],front=0,rear=0;
bool visited[MAX]={false};
int parent[MAX];
for(int i=0;i<g->num;i++){
parent[i]=-1;
}
queue[rear++]=start;
visited[start]=true;
while(front<rear){
int current= queue[front++];
if(current==end)break;
for(int i=0;i<g->num;i++){
if(g->adj[current][i]&&!visited[i]){
queue[rear++]=i;
visited[i]=true;
parent[i]=current;
}
}
}
if(!visited[end]){
printf("No path found\n");

SIDDAVARAM SUPRABHATH YASHASWI 46 1NH23EC155


New Horizon College of Engineering

return;
}
int path[MAX],pathLength=0;
for(int at=end;at!=-1;at=parent[at]){
path[pathLength++]=at;
}
printf("%d\n",pathLength-1);
for(int i=pathLength-1;i>=0;i--){
printf("%d ",path[i]);
}
printf("\n");
}
int main()
{
int num,numf;
scanf("%d",&num);
scanf("%d",&numf);
graph g;
initial(&g,num);
for(int i=0;i<numf;i++){
int u,v;
scanf("%d %d",&u,&v);
add(&g,u,v);
}
int s,e;
scanf("%d %d",&s,&e);
find(&g,s,e);
return 0;
}

Output:

Test case - 1

User Output
4
3
01
12
23
03
3

SIDDAVARAM SUPRABHATH YASHASWI 47 1NH23EC155


New Horizon College of Engineering
0 1 2 3

Test case - 2

User Output
6
6
01
02
13
14
24
35
05
3
0 1 3 5

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 48 1NH23EC155


New Horizon College of Engineering

Program - 10
Date of performance: 5th Jan 2025
Aim:
Develop a program for a city's public transportation system that helps commuters find the shortest travel time
from a single bus stop to all other bus stops using Bellman-Ford.

Input Format:
• First Line: Number of bus stops, n.
• Second Line: Number of edges, m.
• Next m lines: Each edge with its source, destination, and weight (travel time) which are space-separated.
• Next Line: The source bus stop.

Output Format:
• Shortest travel times from the source bus stop to all other bus stops.
• If there is a negative-weight cycle, it will indicate that the graph contains a negative weight cycle.

shortestTravelTime.c

SIDDAVARAM SUPRABHATH YASHASWI 49 1NH23EC155


New Horizon College of Engineering

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#define MAX 100
#define INF INT_MAX
typedef struct Edge{
int src,dest,weight;
}Edge;
Edge edges[MAX];
int dist[MAX];
void bellmanFord(int n,int m,int source){
for(int i=0;i<n;i++)
dist[i]=INF;
dist[source]=0;
for(int i=1;i<=n-1;i++)
{
for(int j=0;j<m;j++)
{
int u=edges[j].src;
int v=edges[j].dest;
int weight=edges[j].weight;
if(dist[u]!=INF&&dist[u]+weight<dist[v])
dist[v]=dist[u]+weight;
}
}
for(int j=0;j<m;j++){
int u=edges[j].src;
int v=edges[j].dest;
int weight=edges[j].weight;
if(dist[u]!=INF&&dist[u]+weight<dist[v]){
printf("Graph contains negative weight cycle\n");
return;
}
}
//printf("%d:\n",source);
for(int i=0;i<n;i++){
if(dist[i]==INF){
printf("%d:INF\n",i);
}
else
printf("%d: %d\n",i,dist[i]);
}
}

SIDDAVARAM SUPRABHATH YASHASWI 50 1NH23EC155


New Horizon College of Engineering

int main(){
int n,m,source;
//printf("Enter the number of bus stops and edges: ");
scanf("%d %d",&n,&m);
//printf("Enter the edges (source destination weight):\n");
for(int i=0;i<m;i++)
scanf("%d %d %d",&edges[i].src,&edges[i].dest,&edges[i].weight);
//printf("Enter the source bus stop: ");
scanf("%d",&source);
bellmanFord(n,m,source);
return 0;
}

Output:

Test case - 1

User Output
4
5
011
024
122
135
231
0
0: 0
1: 1
2: 3
3: 4

Test case - 2

User Output
3
3
0 1 -1
1 2 -1
2 0 -1
0
Graph contains negative weight cycle

SIDDAVARAM SUPRABHATH YASHASWI 51 1NH23EC155


New Horizon College of Engineering

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 52 1NH23EC155


New Horizon College of Engineering

Program - 11
Date of performance: 5th Jan 2025

Aim:
Write a C program to implement unique identifier generation using hashing. Your task is to complete the hash
function to generate a hash value for the provided string.

Input Format:
The input reads the string value.

Output Format:
The output is the final hash value provided by the hash () function, which is an unsigned integer.

uidgenerator.c

SIDDAVARAM SUPRABHATH YASHASWI 53 1NH23EC155


New Horizon College of Engineering

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

struct Identifier {
char input[100];
unsigned int unique_id;
};

// Complete this hash function to generate a hash value from a string


unsigned int hash(const char *str) {

unsigned int hashValue=0;


for(int i=0;str[i]!='\0';i++){
hashValue=hashValue*31+str[i];
}
return hashValue;

unsigned int generate_unique_id(const char *input) {


// Generate a unique identifier based on a string input

// Simply return the hashed value


return hash(input);

int main() {
struct Identifier id;
printf("String: ");
scanf("%99[^\n]", id.input);
id.unique_id = generate_unique_id(id.input);
printf("Unique Identifier for \"%s\": %u\n", id.input,
id.unique_id);
return 0;
}

Output:

Test case - 1

User Output
String:

SIDDAVARAM SUPRABHATH YASHASWI 54 1NH23EC155


New Horizon College of Engineering

Hello World
Unique Identifier for "Hello World": 3432422020

Test case - 2

User Output
String:
CodeTantra
Unique Identifier for "CodeTantra": 1083269839

Test case - 3

User Output
String:
coding
Unique Identifier for "coding": 2939880298

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 55 1NH23EC155


New Horizon College of Engineering

Program - 12
Date of performance: 5th Jan 2025

Aim:
Given a string S of distinct character of size N and their corresponding frequency f[ ] i.e. character S[i] has f[i]
frequency. Your task is to build the Huffman tree and print all the Huffman codes in the preorder traversal of the
tree.

Note: While merging if two nodes have the same value, then the node that occurs at first will be taken on the left
of Binary Tree and the other one to the right, otherwise Node with less value will be taken on the left of the
subtree and other one to the right.

Example 1:
S = "abcdef"
f[] = {5, 9, 12, 13, 16, 45}

Output:
0 100 101 1100 1101 111

CTC36679.c

SIDDAVARAM SUPRABHATH YASHASWI 56 1NH23EC155


New Horizon College of Engineering

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct MinHeapNode{
char data;
unsigned freq;
struct MinHeapNode*left,*right;
};
struct MinHeap{
unsigned size;
unsigned capacity;
struct MinHeapNode**array;
};
struct MinHeapNode*newNode(char data,unsigned freq){
struct MinHeapNode*temp = (struct
MinHeapNode*)malloc(sizeof(struct MinHeapNode));
temp->data = data;
temp->freq = freq;
temp->left = temp->right = NULL;
return temp;
}
struct MinHeap*createMinHeap(unsigned capacity){
struct MinHeap*minHeap = (struct MinHeap*)malloc(
sizeof(struct MinHeap));
minHeap->size = 0;
minHeap->capacity = capacity;
minHeap->array=(struct MinHeapNode**)malloc(minHeap-
>capacity*sizeof(struct MinHeapNode));
return minHeap;
}
void swapMinHeapNode(struct MinHeapNode**a,struct MinHeapNode**b){
struct MinHeapNode*temp = *a;
*a = *b;
*b = temp;
}
void minHeapify(struct MinHeap*minHeap,int idx){
int smallest = idx;
int left = 2*idx + 1;
int right = 2*idx + 2;
if(left < minHeap->size && minHeap->array[left]->freq<minHeap-
>array[smallest]->freq){
smallest = left;
}

SIDDAVARAM SUPRABHATH YASHASWI 57 1NH23EC155


New Horizon College of Engineering

if(right<minHeap->size && minHeap->array[right]->freq<minHeap-


>array[smallest]->freq){
smallest = right;
}
if(smallest != idx){
swapMinHeapNode(&minHeap->array[smallest],&minHeap->array[idx]);
minHeapify(minHeap,smallest);
}
}
int isSizeOne(struct MinHeap*minHeap){
return (minHeap->size == 1);
}
struct MinHeapNode*extractMin(struct MinHeap*minHeap){
struct MinHeapNode*temp = minHeap->array[0];
minHeap->array[0] = minHeap->array[minHeap->size - 1];
--minHeap->size;
minHeapify(minHeap,0);
return temp;
}
void insertMinHeap(struct MinHeap*minHeap,struct
MinHeapNode*minHeapNode){
++minHeap->size;
int i = minHeap->size -1;
while(i && minHeapNode->freq < minHeap->array[(i-1)/2]->freq){
minHeap->array[i]=minHeap->array[(i-1)/2];
i=(i-1)/2;
}
minHeap->array[i] = minHeapNode;
}
void buildMinHeap(struct MinHeap*minHeap){
int n = minHeap->size - 1;
for(int i=(n-1)/2;i>=0;--i){
minHeapify(minHeap,i);
}
}
struct MinHeap*createAndBuildMinHeap(char data[],int freq[],int size){
struct MinHeap*minHeap = createMinHeap(size);
for(int i=0;i<size;i++){
minHeap->array[i] = newNode(data[i],freq[i]);
}
minHeap->size = size;
buildMinHeap(minHeap);
return minHeap;

SIDDAVARAM SUPRABHATH YASHASWI 58 1NH23EC155


New Horizon College of Engineering

}
struct MinHeapNode* buildHuffmanTree(char data[],int freq[],int size){
struct MinHeapNode *left, *right, *top;
struct MinHeap* minHeap =
createAndBuildMinHeap(data,freq,size);
while(!isSizeOne(minHeap)){
left = extractMin(minHeap);
right = extractMin(minHeap);
top = newNode('$' ,left->freq+right->freq);
top->left=left;
top->right=right;
insertMinHeap(minHeap,top);
}
return extractMin(minHeap);
}
void printCodes(struct MinHeapNode* root,int arr[],int top){
static int isFirst = 1;
if(root->left){
arr[top] = 0;
printCodes(root->left,arr,top+1);
}if(root->right){
arr[top] = 1;
printCodes(root->right,arr,top+1);
}
if(!(root->left) && !(root->right)){
if(!isFirst){
printf(" ");
}
isFirst = 0;
for(int i=0;i<top;i++){
printf("%d",arr[i]);
}
}
}
void HuffmanCodes(char data[],int freq[],int size){
struct MinHeapNode* root = buildHuffmanTree(data,freq,size);
int arr[100],top=0;
printCodes(root,arr,top);
}
int main(){
char arr[50];
int freq[50];
scanf(" %s",arr);

SIDDAVARAM SUPRABHATH YASHASWI 59 1NH23EC155


New Horizon College of Engineering

for(int i=0;i<strlen(arr);i++){
scanf(" %d",&freq[i]);
}
HuffmanCodes(arr,freq,strlen(arr));
return 0;
}

Output:

Test case - 1

User Output
abcdef
5 9 12 13 16 45
0 100 101 1100 1101 111

Test case - 2

User Output
hello
32113
00 010 011 10 11

Result:
Thus the above program is executed successfully and the output has been verified

SIDDAVARAM SUPRABHATH YASHASWI 60 1NH23EC155

You might also like