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

DS LAB Journal

The document contains 12 programs written in C programming language demonstrating the use of various data structures and algorithms. The programs cover topics like multidimensional arrays, passing arrays to functions, returning arrays from functions, pointers to arrays, linear search, insertion and deletion in arrays, structures, unions, stacks and queues. For each program, the code is provided along with sample input and output.

Uploaded by

Anjali Anish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
42 views

DS LAB Journal

The document contains 12 programs written in C programming language demonstrating the use of various data structures and algorithms. The programs cover topics like multidimensional arrays, passing arrays to functions, returning arrays from functions, pointers to arrays, linear search, insertion and deletion in arrays, structures, unions, stacks and queues. For each program, the code is provided along with sample input and output.

Uploaded by

Anjali Anish
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 68

Name: Anish Anjali Roll No:21MCA005

DATA STRUCTURE LAB JOURNAL

Program 1: Multidimensional array in c

//multidimensional array in c
// C Program to store and print 12 values entered by the user
#include <stdio.h>
void main()
{
int integer[2][3][2];
printf("Enter 12 values: \n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
scanf("%d", &integer[i][j][k]);
}
}
}
printf("\nDisplaying values:\n");
for (int i = 0; i < 2; ++i)
{
for (int j = 0; j < 3; ++j)
{
for (int k = 0; k < 2; ++k)
{
printf("Integer[%d][%d][%d] = %d\n", i, j, k, integer[i][j][k]);
}
}
}
}

Output:

Page |1
Name: Anish Anjali Roll No:21MCA005

Program 2. Passing array in function in c argument

// Program to calculate the sum of array elements by passing to a function


#include <stdio.h>
float calculateSum(float num[]);
void main() {
float result, num[] = {23.4, 55, 22.6, 3, 40.5, 18};
result = calculateSum(num);
printf("Result = %.2f", result);
}
float calculateSum(float num[]) {
float sum = 0.0;
for (int i = 0; i < 6; ++i) {
sum += num[i];
}
return sum;
}
Output:

Page |2
Name: Anish Anjali Roll No:21MCA005

Program 3. Return array in function from c

#include <stdio.h>
#define MAX_SIZE 10
void getArray(int arr[], int size);
int main()
{
int arr[MAX_SIZE];
int i;
getArray(arr, MAX_SIZE);
printf("Array outside function:");
for (i = 0; i < MAX_SIZE; i++){
printf("%d ", arr[i]);
}
return 0;
}
void getArray(int arr[], int size)
{
int i;
printf("Enter elements in array: ");
for (i = 0; i < size; i++){
scanf("%d", &arr[i]);
}
printf("Array inside function:");
for (i = 0; i < size; i++){
printf("%d ", arr[i]);
}
}

Output:

Page |3
Name: Anish Anjali Roll No:21MCA005

Program 4.Pointer to array in c.

#include <stdio.h>
void main()
{
int i, x[6], sum = 0;
printf("Enter 6 numbers: ");
for(i = 0; i < 6; ++i) {
scanf("%d", x+i);
sum += *(x+i);
}
printf("Sum = %d", sum);
}

Output:

Page |4
Name: Anish Anjali Roll No:21MCA005

Program 5. Linear search in unsorted array

//C program to implement linear search in unsorted array


#include <stdio.h>
#include <conio.h>
void main(){
int inputArray[100], elementCount, counter, num;
printf("Enter Number of Elements in Array\n");
scanf("%d", &elementCount);
printf("Enter %d numbers \n", elementCount);
for(counter = 0; counter < elementCount; counter++){
scanf("%d", &inputArray[counter]);
}
printf("Enter a number to serach in Array\n");
scanf("%d", &num);
for(counter = 0; counter < elementCount; counter++){
if(inputArray[counter] == num){
printf("Number %d found at index %d\n", num, counter);
break;
}
}
if(counter == elementCount){
printf("Number %d Not Present in Input Array\n", num);
}
getch();
}
Output:

Page |5
Name: Anish Anjali Roll No:21MCA005

Program 6. C program to insert an element in an array

#include <stdio.h>
int main()
{
int array[100], position, c, n, value;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);
printf("Enter the location where you wish to insert an element\n");
scanf("%d", &position);
printf("Enter the value to insert\n");
scanf("%d", &value);

for (c = n - 1; c >= position - 1; c--)


array[c+1] = array[c];
array[position-1] = value;
printf("Resultant array is\n");

for (c = 0; c <= n; c++)


printf("%d\n", array[c]);
return 0;
}

Output:

Page |6
Name: Anish Anjali Roll No:21MCA005

Program 7. C program to delete an element in an array

#include <stdio.h>
void main()
{
int array[100], position, c, n;
printf("Enter number of elements in array\n");
scanf("%d", &n);
printf("Enter %d elements\n", n);
for (c = 0; c < n; c++)
scanf("%d", &array[c]);
printf("Enter the location where you wish to delete element\n");
scanf("%d", &position);
if (position >= n+1)
printf("Deletion not possible.\n");
else
{
for (c = position - 1; c < n - 1; c++)
array[c] = array[c+1];
printf("Resultant array:\n");
for (c = 0; c < n - 1; c++)
printf("%d\n", array[c]);
}
}

Output:

Page |7
Name: Anish Anjali Roll No:21MCA005

Program 8. c program using array


#include <stdio.h>
void main()
{
int marks[10], i, n, sum = 0, average;
printf("Enter number of elements: ");
scanf("%d", &n);

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


printf("Enter number%d: ",i+1);
scanf("%d", &marks[i]);
sum += marks[i];
}
average = sum / n;
printf("Average = %d", average);
}

Output:

Page |8
Name: Anish Anjali Roll No:21MCA005

Program 9. Write a program using structure


#include<stdio.h>
struct Student
{
char name[10];
int roll;
};
void show(struct Student st);
void main(){
struct Student std;
printf("\nEnter Student record:\n");
printf("\nStudent name:\t");
scanf("%s", std.name);
printf("\nEnter Student rollno.:\t");
scanf("%d", &std.roll);
show(std);
}
void show(struct Student st)
{
printf("\nstudent name is %s", st.name);
printf("\nroll is %d", st.roll);
}
Output:

Page |9
Name: Anish Anjali Roll No:21MCA005

Program 10. write a program using union


#include<stdio.h>
struct student
{
char name[20];
int rollno;
float marks;
};
struct student s1[3];
void main()
{
int i;
printf("Enter Name, RollNo, and Marks of Three Students:\n");

for(i=0; i<=2; i++)


scanf("%s %d %f",&s1[i].name,&s1[i].rollno,&s1[i].marks);

printf("Student Name\tStudent Roll no\tStudent Marks:");


for(i=0; i<=2; i++)
printf("\n%s\t\t%d\t\t%f", s1[i].name, s1[i].rollno, s1[i].marks);
}

Output:

P a g e | 10
Name: Anish Anjali Roll No:21MCA005

Program 11. program to implement stack operation


// stack implementation:
#include<stdio.h>
#include<stdlib.h>
#define Size 5

int Top=-1, array[Size];


void Push();
void Pop();
void show();

int main()
{
int choice;
while(1)
{
printf("\nOperations performed by Stack");
printf("\n1.Push the element\n2.Pop the element\n3.Show\n4.End");
printf("\n\nEnter the choice:");
scanf("%d",&choice);

switch(choice)
{
case 1: Push();
break;
case 2: Pop();
break;
case 3: show();
break;
case 4: exit(0);

default: printf("\nInvalid choice!!");


}
}
}

void Push()
{
int x;
if(Top==Size-1) {
printf("\n STACK FULL !!");
}
else{
printf("\nEnter element to be inserted to the stack:");
scanf("%d",&x);
Top=Top+1;
array[Top]=x;
}
}

void Pop()

P a g e | 11
Name: Anish Anjali Roll No:21MCA005

{
if(Top==-1) {
printf("\n STACK NOT FULL!!");
}
else {
printf("\n Popped element: %d",array[Top]);
Top=Top-1;
}
}

void show()
{
if(Top==-1){
printf("\nSTACK NOT FULL!!");
}
else{
printf("\nElements present in the stack: \n");
for(int i=Top;i>=0;--i)
printf("%d\n",array[i]);
}
}

Output:

P a g e | 12
Name: Anish Anjali Roll No:21MCA005

Program 12. Write a program for Queue implementation


#include <stdio.h>
#define MAX 10

void insert();
void delete();
void display();
int queue_array[MAX];
int rear = - 1;
int front = - 1;
main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
}
}
}

void insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);

P a g e | 13
Name: Anish Anjali Roll No:21MCA005

rear = rear + 1;
queue_array[rear] = add_item;
}
}
void delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
}
void display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}

Output:

P a g e | 14
Name: Anish Anjali Roll No:21MCA005

Program 13. Write a program to implement circular queue


//Circular Queue using Array
#include<conio.h>
#include<stdio.h>
#include<stdlib.h>
int cqueue[6];
int front = -1, rear = -1, n=6;
void enqueue(int val)
{
if ((front == 0 && rear == n-1) || (front == rear+1))
{
printf("Queue Overflow \n");
return;
}
if (front == -1)
{
front = 0;
rear = 0;
}
else
{
if (rear == n - 1)
rear = 0;
else
rear = rear + 1;
}
cqueue[rear] = val ;
}
void dequeue()
{
if (front == -1)
{
printf("Queue Underflow\n");
return ;
}
printf("Element deleted from queue is : %d ", cqueue[front]);
if (front == rear)
{
front = -1;
rear = -1;
}
else
{
if (front == n - 1)
front = 0;
else
front = front + 1;
}
}

void display()

P a g e | 15
Name: Anish Anjali Roll No:21MCA005

{
int f = front, r = rear;
if (front == -1)
{
printf("Queue is empty");
return;
}
printf("Queue elements are :\n");
if (f <= r)
{
while (f <= r)
{
printf("%d ", cqueue[f]);
f++;
}
}
else
{
while (f <= n - 1)
{
printf("%d ",cqueue[f]);
f++;
}
f = 0;
while (f <= r) {
printf("%d ",cqueue[f]);
f++;
}
}
}

int menu()
{
int choice;
printf("\n 1.Add value to the list");
printf("\n 2. Delete value to the list");
printf("\n 3. View List");
printf("\n 4. Exit\n");
printf("\n Please enter your choice: \t");
scanf("%d",&choice);
return(choice);
}
void main()
{
int value;
while(1)
{
switch(menu())
{
case 1:
printf("Input for insertion: ");

P a g e | 16
Name: Anish Anjali Roll No:21MCA005

scanf("%d",&value);
enqueue(value);
break;
case 2:
dequeue();
break;
case 3:
display();
break;
case 4:
exit(0);
default:
printf("invalid choice");
}
}
}

Output:

P a g e | 17
Name: Anish Anjali Roll No:21MCA005

Program 14. write a program to implement singly linked list


#include <stdio.h>
#include <malloc.h>
#include <stdlib.h>
struct node {
int value;
struct node *next;
};

void insert();
void display();
void delete();
int count();
typedef struct node DATA_NODE;
DATA_NODE *head_node, *first_node, *temp_node = 0, *prev_node, next_node;
int data;

int main()
{
int option = 0;
printf("Singly Linked List :\n");
while (option < 5)
{

printf("\nOptions\n");
printf("1 : Insert into Linked List \n");
printf("2 : Delete from Linked List \n");
printf("3 : Display Linked List\n");
printf("4 : Count Linked List\n");
printf("5: Exit\n");
printf("Enter your option:");
scanf("%d", &option);
switch (option) {
case 1:insert();
break;
case 2:delete();
break;
case 3:display();
break;
case 4:count();
break;
case 5:exit(1);
break;
default:printf("Incorrect Choice.\n");
break;
}
}
return 0;
}

void insert() {

P a g e | 18
Name: Anish Anjali Roll No:21MCA005

printf("\n Enter Element for Inserting in Linked List : \n");


scanf("%d", &data);
temp_node = (DATA_NODE *) malloc(sizeof (DATA_NODE));
temp_node->value = data;
if (first_node == 0) {
first_node = temp_node;
} else {
head_node->next = temp_node;
}
temp_node->next = 0;
head_node = temp_node;
}

void delete() {
int countvalue, pos, i = 0;
countvalue = count();
temp_node = first_node;
printf("\n Enter Position for Delete Element : \n");
scanf("%d", &pos);

if (pos > 0 && pos <= countvalue) {


if (pos == 1) {
temp_node = temp_node -> next;
first_node = temp_node;
printf("\n Deleted Successfully \n\n");
} else {
while (temp_node != 0) {
if (i == (pos - 1)) {
prev_node->next = temp_node->next;
if(i == (countvalue - 1))
{
head_node = prev_node;
}
printf("\n Deleted Successfully \n\n");
break;
} else {
i++;
prev_node = temp_node;
temp_node = temp_node -> next;
}
}
}
} else
printf("\n Invalid Position \n\n");
}

void display() {
int count = 0;
temp_node = first_node;
printf("\n Display Linked List : \n");
while (temp_node != 0) {

P a g e | 19
Name: Anish Anjali Roll No:21MCA005

printf(" %d ", temp_node->value);


count++;
temp_node = temp_node -> next;
}
}

int count() {
int count = 0;
temp_node = first_node;
while (temp_node != 0) {
count++;
temp_node = temp_node -> next;
}
printf("\n No Of Items In Linked List : %d\n", count);
return count;
}

Output:

P a g e | 20
Name: Anish Anjali Roll No:21MCA005

P a g e | 21
Name: Anish Anjali Roll No:21MCA005

Program 15. write a program to implement doubly linked list


// Doubly Linked List
#include <stdio.h>
#include <stdlib.h>
struct node {
int info;
struct node *prev, *next;
};
struct node* start = NULL;
void traverse()
{
if (start == NULL) {
printf("\nList is empty\n");
return;
}

struct node* temp;


temp = start;
while (temp != NULL) {
printf("Data = %d \n", temp->info);
temp = temp->next;
}
}

void insertAtFront()
{
int data;
struct node* temp;
temp = (struct node*)malloc(sizeof(struct node));
printf("\nEnter number to be inserted: ");
scanf("%d", &data);
temp->info = data;
temp->prev = NULL;

temp->next = start;
start = temp;
}

void insertAtEnd()
{
int data;
struct node *temp, *trav;
temp = (struct node*)malloc(sizeof(struct node));
temp->prev = NULL;
temp->next = NULL;
printf("\nEnter number to be inserted: ");
scanf("%d", &data);
temp->info = data;
temp->next = NULL;
trav = start;

P a g e | 22
Name: Anish Anjali Roll No:21MCA005

if (start == NULL) {
start = temp;
}
else {
while (trav->next != NULL)
trav = trav->next;
temp->prev = trav;
trav->next = temp;
}
}
void insertAtPosition()
{
int data, pos, i = 1;
struct node *temp, *newnode;
newnode = malloc(sizeof(struct node));
newnode->next = NULL;
newnode->prev = NULL;

printf("\nEnter position : ");


scanf("%d", &pos);
if (start == NULL) {
start = newnode;
newnode->prev = NULL;
newnode->next = NULL;
}

else if (pos == 1) {
insertAtFront();
}

else {
printf("\nEnter number to be inserted: ");
scanf("%d", &data);
newnode->info = data;
temp = start;
while (i < pos - 1) {
temp = temp->next;
i++;
}
newnode->next = temp->next;
newnode->prev = temp;
temp->next = newnode;
temp->next->prev = newnode;
}
}

void deleteFirst()
{
struct node* temp;
if (start == NULL)
printf("\nList is empty\n");

P a g e | 23
Name: Anish Anjali Roll No:21MCA005

else {
temp = start;
start = start->next;
if (start != NULL)
start->prev = NULL;
free(temp);
}
}

void deleteEnd()
{
struct node* temp;
if (start == NULL)
printf("\nList is empty\n");
temp = start;
while (temp->next != NULL)
temp = temp->next;
if (start->next == NULL)
start = NULL;
else {
temp->prev->next = NULL;
free(temp);
}
}

void deletePosition()
{
int pos, i = 1;
struct node *temp, *position;
temp = start;

if (start == NULL)
printf("\nList is empty\n");

else {

printf("\nEnter position : ");


scanf("%d", &pos);

deleteFirst();
if (start != NULL) {
start->prev = NULL;
}
free(position);
return;
}
while (i < pos - 1) {
temp = temp->next;
i++;
}
position = temp->next;

P a g e | 24
Name: Anish Anjali Roll No:21MCA005

if (position->next != NULL)
position->next->prev = temp;
temp->next = position->next;
free(position);
}

int main()
{
int choice;
while (1) {

printf("\t1. Insert at The Beginning \n");


printf("\t2. Insert at The End \n");
printf("\t3. Insert at Any Position \n");
printf("\t4. Delete from Beginning \n");
printf("\t5. Delete from End \n");
printf("\t6.Delete from Any position \n");
printf("\t7. Display Linked List \n");
printf("\t8. To Exit \n");

printf("\nEnter Choice :\n");


scanf("%d", &choice);

switch (choice) {
case 1:insertAtFront();
break;
case 2:insertAtEnd();
break;
case 3:insertAtPosition();
break;
case 4:deleteFirst();
break;
case 5:deleteEnd();
break;
case 6:deletePosition();
break;
case 7:traverse();
break;
case 8:exit(1);
break;
default:printf("Incorrect Choice. Try Again \n");
continue;
}
}
return 0;
}

Output:

P a g e | 25
Name: Anish Anjali Roll No:21MCA005

P a g e | 26
Name: Anish Anjali Roll No:21MCA005

Program 16. Linear search of an array


#include <stdio.h>
int main()
{
int array[10], search, c, number;
printf("Enter the number of elements in array\n");
scanf("%d",&number);
printf("Enter %d numbers\n", number);
for ( c = 0 ; c < number ; c++ )
scanf("%d",&array[c]);
printf("Enter the number to search\n");
scanf("%d",&search);
for ( c = 0 ; c < number ; c++ )
{
if ( array[c] == search )
{
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if ( c == number )
printf("%d is not present in array.\n", search);
return 0;
}

Output:

P a g e | 27
Name: Anish Anjali Roll No:21MCA005

Program 17. Binary search of an array


#include <stdio.h>
int main()
{
int i, low, high, mid, n, key, array[100];
printf("Enter number of elements: \n");
scanf("%d",&n);
printf("Enter %d integers: \n", n);
for(i = 0; i < n; i++)
scanf("%d",&array[i]);
printf("Enter value to find: \n");
scanf("%d", &key);
low = 0;
high = n - 1;
mid = (low+high)/2;
while (low <= high) {
if(array[mid] < key)
low = mid + 1;
else if (array[mid] == key) {
printf("%d found at location %d. \n", key, mid+1);
break;
}
else
high = mid - 1;
mid = (low + high)/2;
}
if(low > high)
printf("Not found! %d isn't present in the list. \n", key);
return 0;
}

Output:

P a g e | 28
Name: Anish Anjali Roll No:21MCA005

Program 18. Array sorting


//C program to accept N numbers and arrange them in an ascending order
#include <stdio.h>
void main()
{

int i, j, a, n, number[30];
printf("Enter the value of N \n");
scanf("%d", &n);

printf("Enter the numbers \n");


for (i = 0; i < n; ++i)
scanf("%d", &number[i]);
for (i = 0; i < n; ++i)
{
for (j = i + 1; j < n; ++j)
{
if (number[i] > number[j])
{
a = number[i];
number[i] = number[j];
number[j] = a;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; ++i)
printf("%d\n", number[i]);
}

Output:

P a g e | 29
Name: Anish Anjali Roll No:21MCA005

Program 19. Merging of 2 sorted array


#include<stdio.h>
#include<conio.h>
int main()
{
int a[10], b[10], c[20], i, j, limitC, temp;
printf("Enter 10 elements in array A:\n");
for(i=0; i<10; i++)
scanf("%d", &a[i]);
printf("Enter 10 elements in array B:\n");
for(i=0; i<10; i++)
scanf("%d", &b[i]);
printf("\nElements of Array A are:\n");
for(i=0; i<10; i++)
{
if(i==9)
printf("%d", a[i]);
else
printf("%d, ", a[i]);
}
printf("\n\nElements of Array B are:\n");
for(i=0; i<10; i++)
{
if(i==9)
printf("%d", b[i]);
else
printf("%d, ", b[i]);
}

// merging the two arrays


for(i=0; i<10; i++)
c[i] = a[i];
for(j=0; j<10; j++)
{
c[i] = b[j];
i++;
}

// sorting the merged array


for(j=0; j<19; j++)
{
for(i=0; i<19; i++)
{
if(c[i]>c[i+1])
{
temp = c[i];
c[i] = c[i+1];
c[i+1] = temp;
}
}
}

P a g e | 30
Name: Anish Anjali Roll No:21MCA005

printf("\n\nElements of Array C are:\n");


for(i=0; i<20; i++)
{
if(i==19)
printf("%d", c[i]);
else
printf("%d, ", c[i]);
}
getch();
return 0;
}

Output:

P a g e | 31
Name: Anish Anjali Roll No:21MCA005

Program 20. Set implementation using bit string (union, insertion, difference)
#include<stdio.h>
#include<conio.h>
main()
{
int i,j,k,p,ch,n1,n2,set1[10],set2[10], set3[20],flag;
int wish;

printf("\n Enter the size of sets1 \n");


scanf("%d",&n1);
printf("\n Enter the element of set1 \n" );
for(i=0;i<n1;i++)
scanf("%d",&set1[i]);
printf("\n Enter the size of sets2 \n");
scanf("%d",&n2);
printf("\n Enter the elements of set2 \n" );
for(i=0;i<n2;i++)
scanf("%d",&set2[i]);

do
{
printf("\n Menu for set operations");
printf("\n Press 1 for UNION");
printf("\n press 2 for INTERSECTION");
printf("\n press 3 for DIFFERENCE");
printf("\n Enter your Choice");
scanf("%d",&ch);
switch(ch)
{
case 1://for union
k=0;
for(i=0;i<n1;i++)
{
set3[k]=set1[i];
k++;
}
for(i=0;i<n2;i++)
{
flag=1;
for(j=0;j<n1;j++)
{
if(set2[i]==set1[j])
{
flag=0;
break;
}
}
if(flag==1)
{
set3[k]=set2[i];
k++;

P a g e | 32
Name: Anish Anjali Roll No:21MCA005

}
}
p=k;
for(k=0;k <p;k++)
{
printf(" %d",set3[k]);
}
break;
case 2:
k=0;
for(i=0;i<n2;i++)
{
flag=1;
for(j=0;j<n1;j++)
{
if(set2[i]==set1[j])
{
flag=0;
break;
}
}
if(flag==0)
{
set3[k]=set2[i];
k++;
}
}
p=k;
for(k=0;k <p;k++)
{
printf("%d",set3[k]);
}
break;
case 3:
k=0;
for(i=0;i<n1;i++)
{
flag=1;
for(j=0;j<n2;j++)
{
if(set1[i]==set2[j])
{
flag=0;
break;
}
}
if(flag==1)
{
set3[k]=set1[i];
k++;
}

P a g e | 33
Name: Anish Anjali Roll No:21MCA005

}
p=k;
for(k=0;k <p;k++)
{
printf(" %d",set3[k]);
}
break;
}
printf("\n Do you want to continue(0/1)? ");
scanf("%d",&wish);
}
while(wish==0);
}

Output:

P a g e | 34
Name: Anish Anjali Roll No:21MCA005

Program 21. Disjoint set implementation (create, union, find)


#include<stdio.h>
#include<conio.h>
struct disjointSet {
int parent[10];
int rank[10];
int n;
}
dis;
void makeset()
{
int i;
for(i=0;i<dis.n;i++)
dis.parent[i]=i;
dis.rank[i]=0;
}
void displayset()
{
int i;
printf("\nparent array\n");
for(i=0;i<dis.n;i++)
{
printf("%d",dis.parent[i]);
}
printf("\nrank of array\n");
for(i=0;i<dis.n;i++)
{
printf("%d",dis.rank[i]);
}
printf("\n");
}
int find(int x)
{
if(dis.parent[x]!=x)
{
dis.parent[x]=find(dis.parent[x]);
}
return dis.parent[x];
}
void Union(int x,int y)
{
int xset=find(x) , yset=find(y);
if(xset==yset)
return;
if(dis.rank[xset]<dis.rank[yset])
{
dis.parent[xset]=yset;
dis.rank[xset]=-1;
}
else if(dis.rank[xset]>dis.rank[yset])
{

P a g e | 35
Name: Anish Anjali Roll No:21MCA005

dis.parent[yset]=xset;
dis.rank[yset]=-1;
}
else
{
dis.parent[yset]=xset;
dis.rank[xset]=dis.rank[xset]+1;
dis.rank[yset]=-1;
}
}
int main()
{
int x,y,n;
printf("\nenter number of elements :\n");
scanf("%d",&dis.n);
makeset();
int ch,w;
do{
printf("\n1.UNION\n2.FIND \n3.DISPLAY");
printf("\nenter choice :");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nenter elements to perform union :");
scanf("%d%d",&x,&y);
Union(x,y);
break;
case 2:
printf("\nenter elements to check if connected components :");
scanf("%d%d",&x,&y);
if(find(x)==find(y))
printf("\nconnected components !");
else
printf("\n no connected components !");
break;
case 3:
displayset();
break;
}
printf("\n do you want to continue ?(1/0)");
scanf("%d",&w);
}
while(w==1);
return 0;
}

P a g e | 36
Name: Anish Anjali Roll No:21MCA005

Output:

P a g e | 37
Name: Anish Anjali Roll No:21MCA005

Program 22. Implementation of binary search tree


#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node *left, *right;
};
struct node *newNode(int item) {
struct node *temp = (struct node *)malloc(sizeof(struct node));
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
void inorder(struct node *root) {
if (root != NULL) {
inorder(root->left);
printf("%d -> ", root->key);
inorder(root->right);
}
}
struct node *insert(struct node *node, int key) {
if (node == NULL) return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else
node->right = insert(node->right, key);
return node;
}
struct node *minValueNode(struct node *node) {
struct node *current = node;

while (current && current->left != NULL)


current = current->left;
return current;
}
struct node *deleteNode(struct node *root, int key) {
if (root == NULL) return root;
if (key < root->key)
root->left = deleteNode(root->left, key);
else if (key > root->key)
root->right = deleteNode(root->right, key);
else {
if (root->left == NULL) {
struct node *temp = root->right;
free(root);
return temp;
} else if (root->right == NULL) {
struct node *temp = root->left;
free(root);
return temp;
}

P a g e | 38
Name: Anish Anjali Roll No:21MCA005

struct node *temp = minValueNode(root->right);


root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}
void main() {
struct node *root = NULL;
int choice, n;
while(1){
printf(" 1.Insertion");
printf("\n 2.Deleteion");
printf("\n 3.Traversal");
printf("\n 4.Exit");
printf("\nEnter your choice:\n");
scanf("%d",&choice);

switch(choice)

{
case 1: printf("Enter the element to be Inserted:");
scanf("%d",&n);
root = insert(root, n);
break;
case 2: printf("Enter the element to be Deleted:");
scanf("%d",&n);
root = deleteNode(root, n);
break;
case 3: printf("Inorder traversal: ");
inorder(root);
break;
case 4:
exit(0);
break;
default:
printf("n Wrong Choice:n");
break;
}
}
}

P a g e | 39
Name: Anish Anjali Roll No:21MCA005

Output:

P a g e | 40
Name: Anish Anjali Roll No:21MCA005

Program 23. Implementation of balanced binary search tree.


// Checking if a binary tree is height balanced in C
#include <stdio.h>
#include <stdlib.h>
#define bool int
struct node {
int item;
struct node *left;
struct node *right;
};
struct node *newNode(int item) {
struct node *node = (struct node *)malloc(sizeof(struct node));
node->item = item;
node->left = NULL;
node->right = NULL;

return (node);
}
bool checkHeightBalance(struct node *root, int *height) {
int leftHeight = 0, rightHeight = 0;
int l = 0, r = 0;

if (root == NULL) {
*height = 0;
return 1;
}

l = checkHeightBalance(root->left, &leftHeight);
r = checkHeightBalance(root->right, &rightHeight);

*height = (leftHeight > rightHeight ? leftHeight : rightHeight) + 1;

if ((leftHeight - rightHeight >= 2) || (rightHeight - leftHeight >= 2))


return 0;

else
return l && r;
}

int main() {
int height = 0;

struct node *root = newNode(1);


root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);

if (checkHeightBalance(root, &height))
printf("The tree is balanced");
else

P a g e | 41
Name: Anish Anjali Roll No:21MCA005

printf("The tree is not balanced");


}

Output:

P a g e | 42
Name: Anish Anjali Roll No:21MCA005

Program 24. Red black tree implementation


// Implementing Red-Black Tree in C
#include <stdio.h>
#include <stdlib.h>

enum nodeColor {
RED,
BLACK
};

struct rbNode {
int data, color;
struct rbNode *link[2];
};

struct rbNode *root = NULL;

// Create a red-black tree


struct rbNode *createNode(int data) {
struct rbNode *newnode;
newnode = (struct rbNode *)malloc(sizeof(struct rbNode));
newnode->data = data;
newnode->color = RED;
newnode->link[0] = newnode->link[1] = NULL;
return newnode;
}

// Insert an node
void insertion(int data) {
struct rbNode *stack[98], *ptr, *newnode, *xPtr, *yPtr;
int dir[98], ht = 0, index;
ptr = root;
if (!root) {
root = createNode(data);
return;
}

stack[ht] = root;
dir[ht++] = 0;
while (ptr != NULL) {
if (ptr->data == data) {
printf("Duplicates Not Allowed!!\n");
return;
}
index = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
ptr = ptr->link[index];
dir[ht++] = index;
}
stack[ht - 1]->link[index] = newnode = createNode(data);
while ((ht >= 3) && (stack[ht - 1]->color == RED)) {

P a g e | 43
Name: Anish Anjali Roll No:21MCA005

if (dir[ht - 2] == 0) {
yPtr = stack[ht - 2]->link[1];
if (yPtr != NULL && yPtr->color == RED) {
stack[ht - 2]->color = RED;
stack[ht - 1]->color = yPtr->color = BLACK;
ht = ht - 2;
} else {
if (dir[ht - 1] == 0) {
yPtr = stack[ht - 1];
} else {
xPtr = stack[ht - 1];
yPtr = xPtr->link[1];
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
stack[ht - 2]->link[0] = yPtr;
}
xPtr = stack[ht - 2];
xPtr->color = RED;
yPtr->color = BLACK;
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
if (xPtr == root) {
root = yPtr;
} else {
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
} else {
yPtr = stack[ht - 2]->link[0];
if ((yPtr != NULL) && (yPtr->color == RED)) {
stack[ht - 2]->color = RED;
stack[ht - 1]->color = yPtr->color = BLACK;
ht = ht - 2;
} else {
if (dir[ht - 1] == 1) {
yPtr = stack[ht - 1];
} else {
xPtr = stack[ht - 1];
yPtr = xPtr->link[0];
xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = xPtr;
stack[ht - 2]->link[1] = yPtr;
}
xPtr = stack[ht - 2];
yPtr->color = BLACK;
xPtr->color = RED;
xPtr->link[1] = yPtr->link[0];
yPtr->link[0] = xPtr;
if (xPtr == root) {
root = yPtr;

P a g e | 44
Name: Anish Anjali Roll No:21MCA005

} else {
stack[ht - 3]->link[dir[ht - 3]] = yPtr;
}
break;
}
}
}
root->color = BLACK;
}

// Delete a node
void deletion(int data) {
struct rbNode *stack[98], *ptr, *xPtr, *yPtr;
struct rbNode *pPtr, *qPtr, *rPtr;
int dir[98], ht = 0, diff, i;
enum nodeColor color;

if (!root) {
printf("Tree not available\n");
return;
}

ptr = root;
while (ptr != NULL) {
if ((data - ptr->data) == 0)
break;
diff = (data - ptr->data) > 0 ? 1 : 0;
stack[ht] = ptr;
dir[ht++] = diff;
ptr = ptr->link[diff];
}

if (ptr->link[1] == NULL) {
if ((ptr == root) && (ptr->link[0] == NULL)) {
free(ptr);
root = NULL;
} else if (ptr == root) {
root = ptr->link[0];
free(ptr);
} else {
stack[ht - 1]->link[dir[ht - 1]] = ptr->link[0];
}
} else {
xPtr = ptr->link[1];
if (xPtr->link[0] == NULL) {
xPtr->link[0] = ptr->link[0];
color = xPtr->color;
xPtr->color = ptr->color;
ptr->color = color;

if (ptr == root) {

P a g e | 45
Name: Anish Anjali Roll No:21MCA005

root = xPtr;
} else {
stack[ht - 1]->link[dir[ht - 1]] = xPtr;
}

dir[ht] = 1;
stack[ht++] = xPtr;
} else {
i = ht++;
while (1) {
dir[ht] = 0;
stack[ht++] = xPtr;
yPtr = xPtr->link[0];
if (!yPtr->link[0])
break;
xPtr = yPtr;
}

dir[i] = 1;
stack[i] = yPtr;
if (i > 0)
stack[i - 1]->link[dir[i - 1]] = yPtr;

yPtr->link[0] = ptr->link[0];

xPtr->link[0] = yPtr->link[1];
yPtr->link[1] = ptr->link[1];

if (ptr == root) {
root = yPtr;
}

color = yPtr->color;
yPtr->color = ptr->color;
ptr->color = color;
}
}

if (ht < 1)
return;

if (ptr->color == BLACK) {
while (1) {
pPtr = stack[ht - 1]->link[dir[ht - 1]];
if (pPtr && pPtr->color == RED) {
pPtr->color = BLACK;
break;
}

if (ht < 2)
break;

P a g e | 46
Name: Anish Anjali Roll No:21MCA005

if (dir[ht - 2] == 0) {
rPtr = stack[ht - 1]->link[1];

if (!rPtr)
break;

if (rPtr->color == RED) {
stack[ht - 1]->color = RED;
rPtr->color = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];

if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 0;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;

rPtr = stack[ht - 1]->link[1];


}

if ((!rPtr->link[0] || rPtr->link[0]->color == BLACK) &&


(!rPtr->link[1] || rPtr->link[1]->color == BLACK)) {
rPtr->color = RED;
} else {
if (!rPtr->link[1] || rPtr->link[1]->color == BLACK) {
qPtr = rPtr->link[0];
rPtr->color = RED;
qPtr->color = BLACK;
rPtr->link[0] = qPtr->link[1];
qPtr->link[1] = rPtr;
rPtr = stack[ht - 1]->link[1] = qPtr;
}
rPtr->color = stack[ht - 1]->color;
stack[ht - 1]->color = BLACK;
rPtr->link[1]->color = BLACK;
stack[ht - 1]->link[1] = rPtr->link[0];
rPtr->link[0] = stack[ht - 1];
if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
} else {

P a g e | 47
Name: Anish Anjali Roll No:21MCA005

rPtr = stack[ht - 1]->link[0];


if (!rPtr)
break;

if (rPtr->color == RED) {
stack[ht - 1]->color = RED;
rPtr->color = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];

if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
dir[ht] = 1;
stack[ht] = stack[ht - 1];
stack[ht - 1] = rPtr;
ht++;

rPtr = stack[ht - 1]->link[0];


}
if ((!rPtr->link[0] || rPtr->link[0]->color == BLACK) &&
(!rPtr->link[1] || rPtr->link[1]->color == BLACK)) {
rPtr->color = RED;
} else {
if (!rPtr->link[0] || rPtr->link[0]->color == BLACK) {
qPtr = rPtr->link[1];
rPtr->color = RED;
qPtr->color = BLACK;
rPtr->link[1] = qPtr->link[0];
qPtr->link[0] = rPtr;
rPtr = stack[ht - 1]->link[0] = qPtr;
}
rPtr->color = stack[ht - 1]->color;
stack[ht - 1]->color = BLACK;
rPtr->link[0]->color = BLACK;
stack[ht - 1]->link[0] = rPtr->link[1];
rPtr->link[1] = stack[ht - 1];
if (stack[ht - 1] == root) {
root = rPtr;
} else {
stack[ht - 2]->link[dir[ht - 2]] = rPtr;
}
break;
}
}
ht--;
}
}
}

P a g e | 48
Name: Anish Anjali Roll No:21MCA005

// Print the inorder traversal of the tree


void inorderTraversal(struct rbNode *node) {
if (node) {
inorderTraversal(node->link[0]);
printf("%d ", node->data);
inorderTraversal(node->link[1]);
}
return;
}

// Driver code
int main() {
int ch, data;
while (1) {
printf("1. Insertion\t2. Deletion\n");
printf("3. Traverse\t4. Exit");
printf("\nEnter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter the element to insert:");
scanf("%d", &data);
insertion(data);
break;
case 2:
printf("Enter the element to delete:");
scanf("%d", &data);
deletion(data);
break;
case 3:
inorderTraversal(root);
printf("\n");
break;
case 4:
exit(0);
default:
printf("Not available\n");
break;
}
printf("\n");
}
return 0;
}

P a g e | 49
Name: Anish Anjali Roll No:21MCA005

Output:

P a g e | 50
Name: Anish Anjali Roll No:21MCA005

Program 25. B-tree implementation


// Searching a key on a B-tree in C
#include <stdio.h>
#include <stdlib.h>

#define MAX 3
#define MIN 2

struct BTreeNode {
int val[MAX + 1], count;
struct BTreeNode *link[MAX + 1];
};

struct BTreeNode *root;

// Create a node
struct BTreeNode *createNode(int val, struct BTreeNode *child) {
struct BTreeNode *newNode;
newNode = (struct BTreeNode *)malloc(sizeof(struct BTreeNode));
newNode->val[1] = val;
newNode->count = 1;
newNode->link[0] = root;
newNode->link[1] = child;
return newNode;
}

// Insert node
void insertNode(int val, int pos, struct BTreeNode *node,
struct BTreeNode *child) {
int j = node->count;
while (j > pos) {
node->val[j + 1] = node->val[j];
node->link[j + 1] = node->link[j];
j--;
}
node->val[j + 1] = val;
node->link[j + 1] = child;
node->count++;
}

// Split node
void splitNode(int val, int *pval, int pos, struct BTreeNode *node,
struct BTreeNode *child, struct BTreeNode **newNode) {
int median, j;

if (pos > MIN)


median = MIN + 1;
else
median = MIN;

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

P a g e | 51
Name: Anish Anjali Roll No:21MCA005

j = median + 1;
while (j <= MAX) {
(*newNode)->val[j - median] = node->val[j];
(*newNode)->link[j - median] = node->link[j];
j++;
}
node->count = median;
(*newNode)->count = MAX - median;

if (pos <= MIN) {


insertNode(val, pos, node, child);
} else {
insertNode(val, pos - median, *newNode, child);
}
*pval = node->val[node->count];
(*newNode)->link[0] = node->link[node->count];
node->count--;
}

// Set the value


int setValue(int val, int *pval,
struct BTreeNode *node, struct BTreeNode **child) {
int pos;
if (!node) {
*pval = val;
*child = NULL;
return 1;
}

if (val < node->val[1]) {


pos = 0;
} else {
for (pos = node->count;
(val < node->val[pos] && pos > 1); pos--)
;
if (val == node->val[pos]) {
printf("Duplicates are not permitted\n");
return 0;
}
}
if (setValue(val, pval, node->link[pos], child)) {
if (node->count < MAX) {
insertNode(*pval, pos, node, *child);
} else {
splitNode(*pval, pval, pos, node, *child, child);
return 1;
}
}
return 0;
}

P a g e | 52
Name: Anish Anjali Roll No:21MCA005

// Insert the value


void insert(int val) {
int flag, i;
struct BTreeNode *child;

flag = setValue(val, &i, root, &child);


if (flag)
root = createNode(i, child);
}

// Search node
void search(int val, int *pos, struct BTreeNode *myNode) {
if (!myNode) {
return;
}

if (val < myNode->val[1]) {


*pos = 0;
} else {
for (*pos = myNode->count;
(val < myNode->val[*pos] && *pos > 1); (*pos)--)
;
if (val == myNode->val[*pos]) {
printf("%d is found", val);
return;
}
}
search(val, pos, myNode->link[*pos]);

return;
}

// Traverse then nodes


void traversal(struct BTreeNode *myNode) {
int i;
if (myNode) {
for (i = 0; i < myNode->count; i++) {
traversal(myNode->link[i]);
printf("%d ", myNode->val[i + 1]);
}
traversal(myNode->link[i]);
}
}

int main() {
int val, ch;

insert(8);
insert(9);
insert(10);
insert(11);

P a g e | 53
Name: Anish Anjali Roll No:21MCA005

insert(15);
insert(16);
insert(17);
insert(18);
insert(20);
insert(23);

traversal(root);

printf("\n");
search(11, &ch, root);
}

Output:

P a g e | 54
Name: Anish Anjali Roll No:21MCA005

Program 26. Binary heap max implementation


// Max-Heap data structure in C
#include <stdio.h>
int size = 0;
void swap(int *a, int *b)
{
int temp = *b;
*b = *a;
*a = temp;
}
void heapify(int array[], int size, int i)
{
if (size == 1)
{
printf("Single element in the heap");
}
else
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < size && array[l] > array[largest])
largest = l;
if (r < size && array[r] > array[largest])
largest = r;
if (largest != i)
{
swap(&array[i], &array[largest]);
heapify(array, size, largest);
}
}
}
void insert(int array[], int newNum)
{
if (size == 0)
{
array[0] = newNum;
size += 1;
}
else
{
array[size] = newNum;
size += 1;
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
}
}
void deleteRoot(int array[], int num)
{

P a g e | 55
Name: Anish Anjali Roll No:21MCA005

int i;
for (i = 0; i < size; i++)
{
if (num == array[i])
break;
}

swap(&array[i], &array[size - 1]);


size -= 1;
for (int i = size / 2 - 1; i >= 0; i--)
{
heapify(array, size, i);
}
}
void printArray(int array[], int size)
{
for (int i = 0; i < size; ++i)
printf("%d ", array[i]);
printf("\n");
}
int main()
{
int array[10];

insert(array, 3);
insert(array, 4);
insert(array, 9);
insert(array, 5);
insert(array, 2);

printf("Max-Heap array: ");


printArray(array, size);

deleteRoot(array, 4);

printf("After deleting an element: ");

printArray(array, size);
}

Output:

P a g e | 56
Name: Anish Anjali Roll No:21MCA005

27. Fibonacci heap implementation


// Operations on a Fibonacci heap in C

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

typedef struct _NODE {


int key;
int degree;
struct _NODE *left_sibling;
struct _NODE *right_sibling;
struct _NODE *parent;
struct _NODE *child;
bool mark;
bool visited;
} NODE;

typedef struct fibanocci_heap {


int n;
NODE *min;
int phi;
int degree;
} FIB_HEAP;

FIB_HEAP *make_fib_heap();
void insertion(FIB_HEAP *H, NODE *new, int val);
NODE *extract_min(FIB_HEAP *H);
void consolidate(FIB_HEAP *H);
void fib_heap_link(FIB_HEAP *H, NODE *y, NODE *x);
NODE *find_min_node(FIB_HEAP *H);
void decrease_key(FIB_HEAP *H, NODE *node, int key);
void cut(FIB_HEAP *H, NODE *node_to_be_decrease, NODE *parent_node);
void cascading_cut(FIB_HEAP *H, NODE *parent_node);
void Delete_Node(FIB_HEAP *H, int dec_key);

FIB_HEAP *make_fib_heap() {
FIB_HEAP *H;
H = (FIB_HEAP *)malloc(sizeof(FIB_HEAP));
H->n = 0;
H->min = NULL;
H->phi = 0;
H->degree = 0;
return H;
}

// Printing the heap


void print_heap(NODE *n) {
NODE *x;
for (x = n;; x = x->right_sibling) {

P a g e | 57
Name: Anish Anjali Roll No:21MCA005

if (x->child == NULL) {
printf("node with no child (%d) \n", x->key);
} else {
printf("NODE(%d) with child (%d)\n", x->key, x->child->key);
print_heap(x->child);
}
if (x->right_sibling == n) {
break;
}
}
}

// Inserting nodes
void insertion(FIB_HEAP *H, NODE *new, int val) {
new = (NODE *)malloc(sizeof(NODE));
new->key = val;
new->degree = 0;
new->mark = false;
new->parent = NULL;
new->child = NULL;
new->visited = false;
new->left_sibling = new;
new->right_sibling = new;
if (H->min == NULL) {
H->min = new;
} else {
H->min->left_sibling->right_sibling = new;
new->right_sibling = H->min;
new->left_sibling = H->min->left_sibling;
H->min->left_sibling = new;
if (new->key < H->min->key) {
H->min = new;
}
}
(H->n)++;
}

// Find min node


NODE *find_min_node(FIB_HEAP *H) {
if (H == NULL) {
printf(" \n Fibonacci heap not yet created \n");
return NULL;
} else
return H->min;
}

// Union operation
FIB_HEAP *unionHeap(FIB_HEAP *H1, FIB_HEAP *H2) {
FIB_HEAP *Hnew;
Hnew = make_fib_heap();
Hnew->min = H1->min;

P a g e | 58
Name: Anish Anjali Roll No:21MCA005

NODE *temp1, *temp2;


temp1 = Hnew->min->right_sibling;
temp2 = H2->min->left_sibling;

Hnew->min->right_sibling->left_sibling = H2->min->left_sibling;
Hnew->min->right_sibling = H2->min;
H2->min->left_sibling = Hnew->min;
temp2->right_sibling = temp1;

if ((H1->min == NULL) || (H2->min != NULL && H2->min->key < H1->min->key))


Hnew->min = H2->min;
Hnew->n = H1->n + H2->n;
return Hnew;
}

// Calculate the degree


int cal_degree(int n) {
int count = 0;
while (n > 0) {
n = n / 2;
count++;
}
return count;
}

// Consolidate function
void consolidate(FIB_HEAP *H) {
int degree, i, d;
degree = cal_degree(H->n);
NODE *A[degree], *x, *y, *z;
for (i = 0; i <= degree; i++) {
A[i] = NULL;
}
x = H->min;
do {
d = x->degree;
while (A[d] != NULL) {
y = A[d];
if (x->key > y->key) {
NODE *exchange_help;
exchange_help = x;
x = y;
y = exchange_help;
}
if (y == H->min)
H->min = x;
fib_heap_link(H, y, x);
if (y->right_sibling == x)
H->min = x;
A[d] = NULL;

P a g e | 59
Name: Anish Anjali Roll No:21MCA005

d++;
}
A[d] = x;
x = x->right_sibling;
} while (x != H->min);

H->min = NULL;
for (i = 0; i < degree; i++) {
if (A[i] != NULL) {
A[i]->left_sibling = A[i];
A[i]->right_sibling = A[i];
if (H->min == NULL) {
H->min = A[i];
} else {
H->min->left_sibling->right_sibling = A[i];
A[i]->right_sibling = H->min;
A[i]->left_sibling = H->min->left_sibling;
H->min->left_sibling = A[i];
if (A[i]->key < H->min->key) {
H->min = A[i];
}
}
if (H->min == NULL) {
H->min = A[i];
} else if (A[i]->key < H->min->key) {
H->min = A[i];
}
}
}
}

// Linking
void fib_heap_link(FIB_HEAP *H, NODE *y, NODE *x) {
y->right_sibling->left_sibling = y->left_sibling;
y->left_sibling->right_sibling = y->right_sibling;

if (x->right_sibling == x)
H->min = x;

y->left_sibling = y;
y->right_sibling = y;
y->parent = x;

if (x->child == NULL) {
x->child = y;
}
y->right_sibling = x->child;
y->left_sibling = x->child->left_sibling;
x->child->left_sibling->right_sibling = y;
x->child->left_sibling = y;
if ((y->key) < (x->child->key))

P a g e | 60
Name: Anish Anjali Roll No:21MCA005

x->child = y;

(x->degree)++;
}

// Extract min
NODE *extract_min(FIB_HEAP *H) {
if (H->min == NULL)
printf("\n The heap is empty");
else {
NODE *temp = H->min;
NODE *pntr;
pntr = temp;
NODE *x = NULL;
if (temp->child != NULL) {
x = temp->child;
do {
pntr = x->right_sibling;
(H->min->left_sibling)->right_sibling = x;
x->right_sibling = H->min;
x->left_sibling = H->min->left_sibling;
H->min->left_sibling = x;
if (x->key < H->min->key)
H->min = x;
x->parent = NULL;
x = pntr;
} while (pntr != temp->child);
}

(temp->left_sibling)->right_sibling = temp->right_sibling;
(temp->right_sibling)->left_sibling = temp->left_sibling;
H->min = temp->right_sibling;

if (temp == temp->right_sibling && temp->child == NULL)


H->min = NULL;
else {
H->min = temp->right_sibling;
consolidate(H);
}
H->n = H->n - 1;
return temp;
}
return H->min;
}

void cut(FIB_HEAP *H, NODE *node_to_be_decrease, NODE *parent_node) {


NODE *temp_parent_check;

if (node_to_be_decrease == node_to_be_decrease->right_sibling)
parent_node->child = NULL;

P a g e | 61
Name: Anish Anjali Roll No:21MCA005

node_to_be_decrease->left_sibling->right_sibling = node_to_be_decrease->right_sibling;
node_to_be_decrease->right_sibling->left_sibling = node_to_be_decrease->left_sibling;
if (node_to_be_decrease == parent_node->child)
parent_node->child = node_to_be_decrease->right_sibling;
(parent_node->degree)--;

node_to_be_decrease->left_sibling = node_to_be_decrease;
node_to_be_decrease->right_sibling = node_to_be_decrease;
H->min->left_sibling->right_sibling = node_to_be_decrease;
node_to_be_decrease->right_sibling = H->min;
node_to_be_decrease->left_sibling = H->min->left_sibling;
H->min->left_sibling = node_to_be_decrease;

node_to_be_decrease->parent = NULL;
node_to_be_decrease->mark = false;
}

void cascading_cut(FIB_HEAP *H, NODE *parent_node) {


NODE *aux;
aux = parent_node->parent;
if (aux != NULL) {
if (parent_node->mark == false) {
parent_node->mark = true;
} else {
cut(H, parent_node, aux);
cascading_cut(H, aux);
}
}
}

void decrease_key(FIB_HEAP *H, NODE *node_to_be_decrease, int new_key) {


NODE *parent_node;
if (H == NULL) {
printf("\n FIbonacci heap not created ");
return;
}
if (node_to_be_decrease == NULL) {
printf("Node is not in the heap");
}

else {
if (node_to_be_decrease->key < new_key) {
printf("\n Invalid new key for decrease key operation \n ");
} else {
node_to_be_decrease->key = new_key;
parent_node = node_to_be_decrease->parent;
if ((parent_node != NULL) && (node_to_be_decrease->key < parent_node->key)) {
printf("\n cut called");
cut(H, node_to_be_decrease, parent_node);
printf("\n cascading cut called");
cascading_cut(H, parent_node);

P a g e | 62
Name: Anish Anjali Roll No:21MCA005

}
if (node_to_be_decrease->key < H->min->key) {
H->min = node_to_be_decrease;
}
}
}
}

void *find_node(FIB_HEAP *H, NODE *n, int key, int new_key) {


NODE *find_use = n;
NODE *f = NULL;
find_use->visited = true;
if (find_use->key == key) {
find_use->visited = false;
f = find_use;
decrease_key(H, f, new_key);
}
if (find_use->child != NULL) {
find_node(H, find_use->child, key, new_key);
}
if ((find_use->right_sibling->visited != true)) {
find_node(H, find_use->right_sibling, key, new_key);
}

find_use->visited = false;
}

FIB_HEAP *insertion_procedure() {
FIB_HEAP *temp;
int no_of_nodes, ele, i;
NODE *new_node;
temp = (FIB_HEAP *)malloc(sizeof(FIB_HEAP));
temp = NULL;
if (temp == NULL) {
temp = make_fib_heap();
}
printf(" \n enter number of nodes to be insert = ");
scanf("%d", &no_of_nodes);
for (i = 1; i <= no_of_nodes; i++) {
printf("\n node %d and its key value = ", i);
scanf("%d", &ele);
insertion(temp, new_node, ele);
}
return temp;
}
void Delete_Node(FIB_HEAP *H, int dec_key) {
NODE *p = NULL;
find_node(H, H->min, dec_key, -5000);
p = extract_min(H);
if (p != NULL)
printf("\n Node deleted");

P a g e | 63
Name: Anish Anjali Roll No:21MCA005

else
printf("\n Node not deleted:some error");
}

int main(int argc, char **argv) {


NODE *new_node, *min_node, *extracted_min, *node_to_be_decrease, *find_use;
FIB_HEAP *heap, *h1, *h2;
int operation_no, new_key, dec_key, ele, i, no_of_nodes;
heap = (FIB_HEAP *)malloc(sizeof(FIB_HEAP));
heap = NULL;
while (1) {
printf(" \n Operations \n 1. Create Fibonacci heap \n 2. Insert nodes into fibonacci heap \n 3. Find
min \n 4. Union \n 5. Extract min \n 6. Decrease key \n 7.Delete node \n 8. print heap \n 9. exit \n
enter operation_no = ");
scanf("%d", &operation_no);
switch (operation_no) {
case 1:
heap = make_fib_heap();
break;

case 2:
if (heap == NULL) {
heap = make_fib_heap();
}
printf(" enter number of nodes to be insert = ");
scanf("%d", &no_of_nodes);
for (i = 1; i <= no_of_nodes; i++) {
printf("\n node %d and its key value = ", i);
scanf("%d", &ele);
insertion(heap, new_node, ele);
}
break;

case 3:
min_node = find_min_node(heap);
if (min_node == NULL)
printf("No minimum value");
else
printf("\n min value = %d", min_node->key);
break;

case 4:
if (heap == NULL) {
printf("\n no FIbonacci heap created \n ");
break;
}
h1 = insertion_procedure();
heap = unionHeap(heap, h1);
printf("Unified Heap:\n");
print_heap(heap->min);
break;

P a g e | 64
Name: Anish Anjali Roll No:21MCA005

case 5:
if (heap == NULL)
printf("Empty Fibonacci heap");
else {
extracted_min = extract_min(heap);
printf("\n min value = %d", extracted_min->key);
printf("\n Updated heap: \n");
print_heap(heap->min);
}
break;

case 6:
if (heap == NULL)
printf("Fibonacci heap is empty");
else {
printf(" \n node to be decreased = ");
scanf("%d", &dec_key);
printf(" \n enter the new key = ");
scanf("%d", &new_key);
find_use = heap->min;
find_node(heap, find_use, dec_key, new_key);
printf("\n Key decreased- Corresponding heap:\n");
print_heap(heap->min);
}
break;
case 7:
if (heap == NULL)
printf("Fibonacci heap is empty");
else {
printf(" \n Enter node key to be deleted = ");
scanf("%d", &dec_key);
Delete_Node(heap, dec_key);
printf("\n Node Deleted- Corresponding heap:\n");
print_heap(heap->min);
break;
}
case 8:
print_heap(heap->min);
break;

case 9:
free(new_node);
free(heap);
exit(0);

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

P a g e | 65
Name: Anish Anjali Roll No:21MCA005

Output:

P a g e | 66
Name: Anish Anjali Roll No:21MCA005

Program 28. Implementation of Prim’s algorithm


//prims algorithm
#include <limits.h>
#include <stdbool.h>
#include <stdio.h>
#define V 5
int minKey(int key[], bool mstSet[])
{
int min = INT_MAX, min_index;

for (int v = 0; v < V; v++)


if (mstSet[v] == false && key[v] < min)
min = key[v], min_index = v;

return min_index;
}
int printMST(int parent[], int graph[V][V])
{
printf("Edge \tWeight\n");
for (int i = 1; i < V; i++)
printf("%d - %d \t%d \n", parent[i], i, graph[i][parent[i]]);
}
void primMST(int graph[V][V])
{
int parent[V];
int key[V];
bool mstSet[V];
for (int i = 0; i < V; i++)
key[i] = INT_MAX, mstSet[i] = false;
key[0] = 0;
parent[0] = -1;
for (int count = 0; count < V - 1; count++) {
int u = minKey(key, mstSet);
mstSet[u] = true;
for (int v = 0; v < V; v++)
if (graph[u][v] && mstSet[v] == false && graph[u][v] < key[v])
parent[v] = u, key[v] = graph[u][v];
}
printMST(parent, graph);
}
int main()
{
int graph[V][V] = { { 0, 2, 0, 6, 0 },
{ 2, 0, 3, 8, 5 },
{ 0, 3, 0, 0, 7 },
{ 6, 8, 0, 0, 9 },
{ 0, 5, 7, 9, 0 } };
primMST(graph);

return 0;
}

P a g e | 67
Name: Anish Anjali Roll No:21MCA005

Output:

P a g e | 68

You might also like