0% found this document useful (0 votes)
8 views35 pages

Student Attendance and Sorting Programs

The document contains a series of practical programming exercises involving various data structures and algorithms. It includes programs for searching student roll numbers using linear and binary search, sorting student percentages with selection and bubble sort, implementing a telephone book database with hash tables, managing club members with singly linked lists, and creating a ticket booking system using doubly linked lists. Each practical includes code snippets and descriptions of the functionality implemented.

Uploaded by

guse4373
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)
8 views35 pages

Student Attendance and Sorting Programs

The document contains a series of practical programming exercises involving various data structures and algorithms. It includes programs for searching student roll numbers using linear and binary search, sorting student percentages with selection and bubble sort, implementing a telephone book database with hash tables, managing club members with singly linked lists, and creating a ticket booking system using doubly linked lists. Each practical includes code snippets and descriptions of the functionality implemented.

Uploaded by

guse4373
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

Practical No.

1
A) Write a program to store roll numbers of student in array who attended a
training program in random order. Write a function for searching whether
a particular student attended a training program or not, using Linear search.

Code :

#include <stdio.h>
void linearSearch(int arr[], int n, int key) {
int found = 0;

for (int i = 0; i < n; i++) {


if (arr[i] == key) {
found = 1;
break;
}
}

if (found)
printf("Student with roll number %d attended the training program.\n", key);
else
printf("Student with roll number %d did NOT attend the training program.\n",
key);
}
int main() {
int n, key;
printf("Enter number of students who attended the training: ");
scanf("%d", &n);

int rollNumbers[n];
printf("Enter roll numbers of students:\n");
for (int i = 0; i < n; i++) {
scanf("%d", &rollNumbers[i]);
}
printf("Enter roll number to search: ");
scanf("%d", &key);

linearSearch(rollNumbers, n, key);

return 0;
}
B) Write a program to store roll numbers of student array who attended
training programs in sorted order. Write a function for searching whether a
particular student attended a training program or not, using Binary search.

Code

#include <stdio.h>
int binarySearch(int arr[], int size, int key) {
int low = 0, high = size - 1;
while (low <= high) {
int mid = (low + high) / 2;
if (arr[mid] == key)
return mid; // Student found
else if (arr[mid] < key)
low = mid + 1;
else
high = mid - 1;
}
return -1;
}

int main() {
int n, i, roll;
printf("Enter number of students attended training: ");
scanf("%d", &n);
int rolls[n];
printf("Enter roll numbers in sorted order:\n");
for (i = 0; i < n; i++) {
scanf("%d", &rolls[i]);
}
printf("Enter roll number to search: ");
scanf("%d", &roll);

int result = binarySearch(rolls, n, roll);

if (result != -1)
printf("Student with roll number %d attended the training.\n", roll);
else
printf("Student with roll number %d did NOT attend the training.\n", roll);

return 0;
}
Practical No.2
Write a program to store the first year percentage of students in an array. Write
function for sorting array of floating point numbers in ascending order using -
Selection Sort -
Bubble sort and display top five scores
Code
#include <stdio.h>

void selectionSort(float arr[], int n) {

int i, j, minIndex;

float temp;

for (i = 0; i < n-1; i++) {

minIndex = i;
for (j = i+1; j < n; j++) {

if (arr[j] < arr[minIndex])

minIndex = j;

temp = arr[i];

arr[i] = arr[minIndex];

arr[minIndex] = temp;
}

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

int i, j;

float temp;

for (i = 0; i < n-1; i++) {

for (j = 0; j < n-i-1; j++) {

if (arr[j] > arr[j+1]) {


// Swap
temp = arr[j];
arr[j] = arr[j+1];

arr[j+1] = temp;

}
}

void displayTopFive(float arr[], int n) {

printf("Top 5 scores:\n");

int start = n-5;

if(start < 0) start = 0; // In case less than 5 students

for(int i = n-1; i >= start; i--) {


printf("%.2f\n", arr[i]);
}

int main() {

int n;

printf("Enter number of students: ");

scanf("%d", &n);

float percentages[n];

printf("Enter the percentages of %d students:\n", n);

for(int i=0; i<n; i++) {

scanf("%f", &percentages[i]);

float selectionArr[n];

for(int i=0; i<n; i++) selectionArr[i] = percentages[i];


selectionSort(selectionArr, n);

printf("\nUsing Selection Sort:\n");


displayTopFive(selectionArr, n);
float bubbleArr[n];

for(int i=0; i<n; i++) bubbleArr[i] = percentages[i];

bubbleSort(bubbleArr, n);

printf("\nUsing Bubble Sort:\n");


displayTopFive(bubbleArr, n);

return 0;

}
Practical No.3
Consider the telephone book database of N clients. Make use of a hash table
implementation to quickly look up a client’s telephone number. Make use of
linear probing, double hashing and quadratic collision handling techniques.
Code
#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#define SIZE 10 // Size of the hash table

typedef struct {

char name[50];
char phone[15];

} Client;

Client hashTable[SIZE];

void initTable() {

for (int i = 0; i < SIZE; i++) {

hashTable[i].name[0] = '\0';

hashTable[i].phone[0] = '\0';
}

int hashFunction(char *key) {

int sum = 0;

for (int i = 0; key[i] != '\0'; i++) {

sum += key[i];

}
return sum % SIZE;

void insertLinear(char *name, char *phone) {


int index = hashFunction(name);
int originalIndex = index;

while (hashTable[index].name[0] != '\0') {

index = (index + 1) % SIZE;

if (index == originalIndex) {
printf("Hash table full!\n");

return;

strcpy(hashTable[index].name, name);

strcpy(hashTable[index].phone, phone);

}
void insertQuadratic(char *name, char *phone) {
int index = hashFunction(name);

int i = 0;

while (hashTable[(index + i * i) % SIZE].name[0] != '\0') {

i++;

if (i == SIZE) {

printf("Hash table full!\n");

return;
} }

index = (index + i * i) % SIZE;

strcpy(hashTable[index].name, name);

strcpy(hashTable[index].phone, phone);

int secondHash(char *key) {

int sum = 0;
for (int i = 0; key[i] != '\0'; i++)

sum += key[i];
return 7 - (sum % 7); // secondary hash (prime < SIZE)
}

void insertDoubleHash(char *name, char *phone) {

int index = hashFunction(name);

int step = secondHash(name);


int originalIndex = index;

while (hashTable[index].name[0] != '\0') {

index = (index + step) % SIZE;

if (index == originalIndex) {

printf("Hash table full!\n");

return;

} }
strcpy(hashTable[index].name, name);
strcpy(hashTable[index].phone, phone);

void searchClient(char *name) {

int index = hashFunction(name);

int i = 0;

while (i < SIZE) {

int try = (index + i) % SIZE; // linear probing search


if (strcmp(hashTable[try].name, name) == 0) {

printf("Client Found: %s -> %s\n", hashTable[try].name, hashTable[try].phone);

return;

i++;

printf("Client not found!\n"); }


void display() {

printf("\nHash Table:\n");
for (int i = 0; i < SIZE; i++) {
if (hashTable[i].name[0] != '\0')

printf("%d -> %s : %s\n", i, hashTable[i].name, hashTable[i].phone);

else

printf("%d -> Empty\n", i);


}}

int main() {

initTable();

insertLinear("Alice", "1234567890");

insertLinear("Bob", "2345678901");

insertLinear("Charlie", "3456789012");

display();
searchClient("Bob");
searchClient("David");

return 0;

}
Practical No. 4
The Department of Computer Engineering has a student’s club named
Pinnacle Club Students of the second, third and final year of the department can
be granted membership on request. Similarly one may cancel the membership of
the club. First node is reserved for the president of the club and the last node is
reserved for the secretary of the club. Write a program to maintain club member
‘s information using singly linked lists. Store student PRN and Name. Write
functions to: a) Add and delete the members as well as president or even secretary.
b) Compute total number of members of club c) Display members d) Two linked
lists exist for two divisions. Concatenate two lists.

Code
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

typedef struct Node {

char prn[15];

char name[50];
struct Node* next;

} Node;

Node* createNode(char prn[], char name[]) {

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

strcpy(newNode->prn, prn);
strcpy(newNode->name, name);

newNode->next = NULL;
return newNode;

void addPresident(Node** head, char prn[], char name[]) {

Node* newNode = createNode(prn, name);


newNode->next = *head;
*head = newNode;

printf("President added.\n");

void addSecretary(Node** head, char prn[], char name[]) {


Node* newNode = createNode(prn, name);

if (*head == NULL) {

*head = newNode;

return;

Node* temp = *head;

while (temp->next != NULL) {


temp = temp->next;
}

temp->next = newNode;

printf("Secretary added.\n");

void addMember(Node** head, char prn[], char name[]) {

Node* newNode = createNode(prn, name);

if (*head == NULL) {
*head = newNode;

return;

Node* temp = *head;

while (temp->next != NULL && temp->next->next != NULL) {

temp = temp->next;

}
newNode->next = temp->next;

temp->next = newNode;
printf("Member added.\n");
}

void deleteMember(Node** head, char prn[]) {

if (*head == NULL) {

printf("List is empty.\n");
return;

Node* temp = *head;

Node* prev = NULL;

if (strcmp(temp->prn, prn) == 0) {

*head = temp->next;

free(temp);
printf("Member deleted.\n");
return;

while (temp != NULL && strcmp(temp->prn, prn) != 0) {

prev = temp;

temp = temp->next;

if (temp == NULL) {

printf("Member not found.\n");


return;

prev->next = temp->next;

free(temp);

printf("Member deleted.\n");

int countMembers(Node* head) {


int count = 0;

Node* temp = head;


while (temp != NULL) {
count++;

temp = temp->next;

return count;
}

void displayMembers(Node* head) {

if (head == NULL) {

printf("List is empty.\n");

return;

Node* temp = head;


printf("PRN\tName\n");
printf("--------------------------\n");

while (temp != NULL) {

printf("%s\t%s\n", temp->prn, temp->name);

temp = temp->next;

Node* concatenateLists(Node* list1, Node* list2) {


if (list1 == NULL) return list2;

Node* temp = list1;

while (temp->next != NULL) {

temp = temp->next;

temp->next = list2;

return list1;
}

int main() {
Node* divisionA = NULL;
Node* divisionB = NULL;

addPresident(&divisionA, "1001", "Alice");

addMember(&divisionA, "1002", "Bob");

addSecretary(&divisionA, "1003", "Charlie");


addPresident(&divisionB, "2001", "David");

addMember(&divisionB, "2002", "Eve");

addSecretary(&divisionB, "2003", "Frank");

printf("Division A Members:\n");

displayMembers(divisionA);

printf("\nDivision B Members:\n");

displayMembers(divisionB);
Node* combined = concatenateLists(divisionA, divisionB);
printf("\nCombined Club Members:\n");

displayMembers(combined);

printf("\nTotal Members: %d\n", countMembers(combined));

deleteMember(&combined, "1002");

printf("\nAfter deleting PRN 1002:\n");

displayMembers(combined);

printf("\nTotal Members: %d\n", countMembers(combined));


return 0;

}
Practical No. 5

The ticket booking system of Cinemax theater has to be implemented. There are
10 rows and 7 seats in each row. Doubly linked list has to be maintained to keep
track of free seats in rows. Assume some random booking to start with. Use an
array to store pointers (Head pointer) to each row. On demand
a) The list of available seats is to be displayed b) The seats are to be booked c)
The booking can be cancelled.

Code
#include <stdio.h>

#include <stdlib.h>

#define ROWS 10

#define SEATS 7
typedef struct Seat {

int seatNo;

int booked; // 0 = free, 1 = booked

struct Seat* prev;

struct Seat* next;

} Seat;

Seat* createRow() {

Seat* head = NULL;


Seat* prev = NULL;

for (int i = 1; i <= SEATS; i++) {

Seat* newSeat = (Seat*)malloc(sizeof(Seat));

newSeat->seatNo = i;

newSeat->booked = rand() % 2; // Random booking (0 or 1)

newSeat->prev = prev;

newSeat->next = NULL;
if (prev != NULL)
prev->next = newSeat;
else

head = newSeat;

prev = newSeat;

}
return head;

void displayAvailableSeats(Seat* row, int rowNo) {

printf("Row %d available seats: ", rowNo + 1);

Seat* temp = row;

int available = 0;

while (temp != NULL) {


if (temp->booked == 0) {
printf("%d ", temp->seatNo);

available = 1;

temp = temp->next;

if (!available) printf("None");

printf("\n");
}

void bookSeat(Seat* row, int seatNo) {

Seat* temp = row;

while (temp != NULL) {

if (temp->seatNo == seatNo) {

if (temp->booked == 0) {

temp->booked = 1;
printf("Seat %d booked successfully.\n", seatNo);

} else {
printf("Seat %d is already booked.\n", seatNo);
}

return;

temp = temp->next;
}

printf("Seat %d not found.\n", seatNo);

void cancelBooking(Seat* row, int seatNo) {

Seat* temp = row;

while (temp != NULL) {

if (temp->seatNo == seatNo) {
if (temp->booked == 1) {
temp->booked = 0;

printf("Booking of seat %d cancelled.\n", seatNo);

} else {

printf("Seat %d is already free.\n", seatNo);

return;

}
temp = temp->next;

printf("Seat %d not found.\n", seatNo);

int main() {

Seat* theater[ROWS];

for (int i = 0; i < ROWS; i++) {


theater[i] = createRow();

}
int choice, rowNo, seatNo;
do {

printf("\nCinemax Ticket Booking System\n");

printf("1. Display Available Seats\n");

printf("2. Book a Seat\n");


printf("3. Cancel Booking\n");

printf("4. Exit\n");

printf("Enter your choice: ");

scanf("%d", &choice);

switch (choice) {

case 1:

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


displayAvailableSeats(theater[i], i);
break;

case 2:

printf("Enter Row (1-10): ");

scanf("%d", &rowNo);

printf("Enter Seat Number (1-7): ");

scanf("%d", &seatNo);

if (rowNo >= 1 && rowNo <= ROWS && seatNo >= 1 && seatNo <= SEATS)
bookSeat(theater[rowNo - 1], seatNo);

else

printf("Invalid row or seat number.\n");

break;

case 3:

printf("Enter Row (1-10): ");

scanf("%d", &rowNo);
printf("Enter Seat Number (1-7): ");

scanf("%d", &seatNo);
if (rowNo >= 1 && rowNo <= ROWS && seatNo >= 1 && seatNo <= SEATS)
cancelBooking(theater[rowNo - 1], seatNo);

else

printf("Invalid row or seat number.\n");

break;
case 4:

printf("Exiting...\n");

break;

default:

printf("Invalid choice.\n");

} while (choice != 4);


return 0;
}
Practical No. 6
In any language program mostly syntax error occurs due to unbalancing delimiter
such as (), {}, []. Write a program using stack to check whether a given expression
is well parenthesized or not.
Code:
#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define MAX 100

typedef struct {

char items[MAX];
int top;

} Stack;

void initStack(Stack* s) {

s->top = -1;

int isEmpty(Stack* s) {

return s->top == -1;


}

void push(Stack* s, char c) {

if (s->top == MAX - 1) {

printf("Stack Overflow\n");

return;

s->items[++(s->top)] = c;
}

char pop(Stack* s) {

if (isEmpty(s)) {
return '\0';
}

return s->items[(s->top)--];

int isMatchingPair(char open, char close) {


if (open == '(' && close == ')') return 1;

if (open == '{' && close == '}') return 1;

if (open == '[' && close == ']') return 1;

return 0;

int isWellParenthesized(char* expr) {

Stack s;
initStack(&s);
for (int i = 0; expr[i] != '\0'; i++) {

char ch = expr[i];

if (ch == '(' || ch == '{' || ch == '[') {

push(&s, ch); // Push opening delimiter

} else if (ch == ')' || ch == '}' || ch == ']') {

if (isEmpty(&s) || !isMatchingPair(pop(&s), ch)) {

return 0; // Not balanced


}} }

return isEmpty(&s);

int main() {

char expr[MAX];

printf("Enter an expression: ");

scanf("%s", expr);
if (isWellParenthesized(expr)) {

printf("The expression is well-parenthesized.\n");


} else {
printf("The expression is NOT well-parenthesized.\n");

return 0;

}
Practical No. 7
Pizza parlor accepting maximum M orders. Orders are served on a first come first
served basis. Queues are frequently used in computer programming, and a typical
example is the creation of a job queue by an operating system. If the operating
system does not use priorities, then the jobs are processed in the order they enter
the system. Write a program for simulating job queue. Write functions to add jobs
and delete jobs from the queue.

Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX 10
typedef struct {
int front, rear;
char jobs[MAX][50];
} Queue;
void initQueue(Queue* q) {
q->front = -1;
q->rear = -1;
}
int isEmpty(Queue* q) {
return q->front == -1;
}
int isFull(Queue* q) {
return q->rear == MAX - 1;
}
void addJob(Queue* q, char job[]) {
if (isFull(q)) {
printf("Queue is full! Cannot add more jobs.\n");
return;
}
if (isEmpty(q)) {
q->front = 0;
}
q->rear++;
strcpy(q->jobs[q->rear], job);
printf("Job '%s' added to the queue.\n", job);
}
void deleteJob(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty! No job to serve.\n");
return;
}
printf("Job '%s' served and removed from the queue.\n", q->jobs[q->front]);
if (q->front == q->rear) {
// Queue becomes empty
q->front = -1;
q->rear = -1;
} else {
q->front++;
}
}
void displayQueue(Queue* q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return;
}
printf("Current Jobs in Queue:\n");
for (int i = q->front; i <= q->rear; i++) {
printf("%d. %s\n", i - q->front + 1, q->jobs[i]);
}
}
int main() {
Queue pizzaQueue;
initQueue(&pizzaQueue);
int choice;
char job[50];
do {
printf("\nPizza Parlor Job Queue System\n");
printf("1. Add Job\n");
printf("2. Serve Job\n");
printf("3. Display Jobs\n");
printf("4. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);
getchar(); // consume newline
switch (choice) {
case 1:
printf("Enter job description: ");
fgets(job, sizeof(job), stdin);
job[strcspn(job, "\n")] = '\0'; // Remove newline
addJob(&pizzaQueue, job);
break;
case 2:
deleteJob(&pizzaQueue);
break;
case 3:
displayQueue(&pizzaQueue);
break;
case 4:
printf("Exiting...\n");
break;
default:
printf("Invalid choice! Try again.\n");
}
} while (choice != 4);

return 0;
}
Practical No. 8
Beginning with an empty binary search tree, Construct a binary search tree by
inserting the values in the order given. After constructing a binary tree -
i. Insert new node
ii. Find number of nodes in longest path from root
iii. Minimum data value found in the tree
iv. Change a tree so that the roles of the left and right pointers are swapped at
every node
v. Search a value.

Code
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node* left;
struct Node* right;
} Node;
Node* createNode(int data) {
Node* newNode = (Node*)malloc(sizeof(Node));
newNode->data = data;
newNode->left = newNode->right = NULL;
return newNode;
}
Node* insertNode(Node* root, int data) {
if (root == NULL) return createNode(data);
if (data < root->data)
root->left = insertNode(root->left, data);
else if (data > root->data)
root->right = insertNode(root->right, data);
return root; }
int height(Node* root) {
if (root == NULL) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
return (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;
}
int findMin(Node* root) {
if (root == NULL) {
printf("Tree is empty.\n");
return -1;
}
Node* temp = root;
while (temp->left != NULL)
temp = temp->left;
return temp->data;
}
void mirrorTree(Node* root) {
if (root == NULL) return;
Node* temp = root->left;
root->left = root->right;
root->right = temp;
mirrorTree(root->left);
mirrorTree(root->right);
}
int search(Node* root, int key) {
if (root == NULL) return 0;
if (root->data == key) return 1;
if (key < root->data) return search(root->left, key);
else return search(root->right, key);
}
void inorder(Node* root) {
if (root == NULL) return;
inorder(root->left);
printf("%d ", root->data);
inorder(root->right);
}
int main() {
Node* root = NULL;
int values[] = {50, 30, 70, 20, 40, 60, 80};
int n = sizeof(values)/sizeof(values[0]);
for (int i = 0; i < n; i++) {
root = insertNode(root, values[i]);
}
printf("Inorder traversal of BST: ");
inorder(root);
printf("\n");
int newValue;
printf("Enter a value to insert: ");
scanf("%d", &newValue);
root = insertNode(root, newValue);
printf("Inorder after insertion: ");
inorder(root);
printf("\n");
printf("Height of BST: %d\n", height(root));
printf("Minimum value in BST: %d\n", findMin(root));
mirrorTree(root);
printf("Inorder traversal after mirroring: ");
inorder(root);
printf("\n");
int key;
printf("Enter value to search: ");
scanf("%d", &key);
if (search(root, key))
printf("%d is found in BST.\n", key);
else
printf("%d is not found in BST.\n", key);

return 0;
}
Practical No. 9
There are flight paths between cities. If there is a flight between city A and city B
then there is an edge between the cities. The cost of the edge can be the time that
flight takes to reach city B from A or the amount of fuel used for the journey.
Represent this as a graph. The node can be represented by the airport name or
name of the city. Use adjacency list representation of the graph or use adjacency
matrix representation of the graph. Check whether the graph is connected or not.
Code
#include <stdio.h>
#include <stdlib.h>
#define MAX 10
void createGraph(int adj[MAX][MAX], int n);
void displayGraph(int adj[MAX][MAX], int n);
void DFS(int adj[MAX][MAX], int visited[MAX], int start, int n);
int isConnected(int adj[MAX][MAX], int n);
int main() {
int adj[MAX][MAX];
int n;
printf("Enter number of cities: ");
scanf("%d", &n);
createGraph(adj, n);
printf("\nAdjacency Matrix Representation:\n");
displayGraph(adj, n);
if (isConnected(adj, n))
printf("\nThe graph is connected.\n");
else
printf("\nThe graph is NOT connected.\n");
return 0;
}
void createGraph(int adj[MAX][MAX], int n) {
int i, j;
printf("\nEnter the adjacency matrix (Enter 0 if no flight, else enter cost):\n");
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
scanf("%d", &adj[i][j]);
}
}}
void displayGraph(int adj[MAX][MAX], int n) {
int i, j;
for (i = 0; i < n; i++) {
for (j = 0; j < n; j++) {
printf("%d\t", adj[i][j]);
}
printf("\n");
}}
void DFS(int adj[MAX][MAX], int visited[MAX], int start, int n) {
visited[start] = 1;
for (int i = 0; i < n; i++) {
if (adj[start][i] != 0 && !visited[i]) {
DFS(adj, visited, i, n);
} } }
int isConnected(int adj[MAX][MAX], int n) {
int visited[MAX] = {0};
DFS(adj, visited, 0, n);
for (int i = 0; i < n; i++) {
if (!visited[i])
return 0; // Not all nodes visited
}
return 1;
}
OR

You have a business with several offices; you want to lease phone lines to connect
them up with each other; and the phone company charges different amounts of
money to connect different pairs of cities. You want a set of lines that connects
all your offices With a minimum total cost. Solve the problem by suggesting
appropriate data structures.

write c program to represent phone line to connect them up with each other that
connects all offices with a minimum total cost of a graph solve the problem by
suggesting appropriate data structures

Code
#include <stdio.h>
#include <stdlib.h>
typedef struct {
int src, dest, cost;
} Edge;
typedef struct {
int parent;
int rank;
}
Subset;
int compareEdges(const void* a, const void* b) {
Edge* e1 = (Edge*)a;
Edge* e2 = (Edge*)b;
return e1->cost - e2->cost;
}
int find(Subset subsets[], int i) {
if (subsets[i].parent != i)
subsets[i].parent = find(subsets, subsets[i].parent);
return subsets[i].parent;
}
void unionSets(Subset subsets[], int x, int y) {
int xroot = find(subsets, x);
int yroot = find(subsets, y);

if (subsets[xroot].rank < subsets[yroot].rank)


subsets[xroot].parent = yroot;
else if (subsets[xroot].rank > subsets[yroot].rank)
subsets[yroot].parent = xroot;
else {
subsets[yroot].parent = xroot;
subsets[xroot].rank++;
}
}
void kruskalMST(Edge edges[], int V, int E) {
qsort(edges, E, sizeof(Edge), compareEdges);
Subset* subsets = (Subset*)malloc(V * sizeof(Subset));
for (int v = 0; v < V; v++) {
subsets[v].parent = v;
subsets[v].rank = 0;
}
Edge* result = (Edge*)malloc((V - 1) * sizeof(Edge));
int e = 0; // index for result
int i = 0; // index for sorted edges
while (e < V - 1 && i < E) {
Edge next_edge = edges[i++];
int x = find(subsets, next_edge.src);
int y = find(subsets, next_edge.dest);
if (x != y) {
result[e++] = next_edge;
unionSets(subsets, x, y);
}
}
printf("Edges in Minimum Spanning Tree:\n");
int minimumCost = 0;
for (i = 0; i < e; i++) {
printf("%d -- %d == %d\n", result[i].src, result[i].dest, result[i].cost);
minimumCost += result[i].cost;
}
printf("Minimum total cost = %d\n", minimumCost);

free(subsets);
free(result);
}
int main() {
int V, E;
printf("Enter number of offices (vertices): ");
scanf("%d", &V);
printf("Enter number of possible connections (edges): ");
scanf("%d", &E);

Edge* edges = (Edge*)malloc(E * sizeof(Edge));

printf("Enter edges (source destination cost):\n");


for (int i = 0; i < E; i++) {
scanf("%d %d %d", &edges[i].src, &edges[i].dest, &edges[i].cost);
}
kruskalMST(edges, V, E);
free(edges);
return 0;
}

You might also like