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

INDEX

S.NO. DATE TITLE PAGE MARKS SIGNATURE


NO.
1. INFIX TO POSTFIX EXPRESSION
1
EVALUATION OF POSTFIX
2. 4
EXPRESSION

3. CIRCULAR QUEUE 6

4. PRIORITY QUEUE 9

5. DEQUE DATA STRUCTURE 13

6. BINARY TREE 19

7. BINARY SEARCH TREE 22

8. AVL TREE 28

9. B TREE 34

10. BREADTH FIRST SEARCH 39

11. DEPTH FIRST SEARCH 41

12. TOPOLOGICAL SORT 44

13. PRIM’S ALGORITHM 48

14. KRUSKAL’S ALGORITHM 51

15. TRAVELLING SALESMAN PROBLEM 54


Ex. No. 01 INFIX TO POSTFIX EXPRESSION
Date:

Aim:
To write a C program to convert the infix expression into postfix expression.

Algorithm:
1. Start
2. Push “(“onto stack and add “)” to the end of “X”.
3. Scan “X” from left to right and repeat step 4 to 7 for each element of “X” until the stack is empty.
4. If operator found, add it to Y.
5. And if left parenthesis found, push it onto Stack.
6. If an operator found, then:
a. Repeatedly pop from stack and add to “Y” each operator (on the top of stack) which has the same
precedence as or higher precedence than operator.
b. Add operator to Stack. [End of If block]
7. If a right parenthesis found, then:
a. Repeatedly pop from Stack and add to Y each operator (on the top of Stack) until a left parenthesis
is found.
b. Remove the left Parenthesis.
[End of If block]
[End of If block]
8. Stop.

Program:
#include<stdio.h>
#include<ctype.h>

char stack[100]; int top = -1;


void push(char x)
{
stack[++top] = x;
}

char pop()
{
if(top == -1)
return -1;
else
return stack[top--];
}

1
int priority(char x)
{
if(x == '(')
return 0;
if(x == '&' || x == '|')
return 1;
if(x == '+' || x == '-')
return 2;
if(x == '*' || x == '/' || x == '%')
return 3;
if(x == '^')
return 4;
return 0;
}

char IntoPost(char *exp)


{
char *e, x; e = exp;
while(*e != '\0')
{
if(isalnum(*e))
printf("%c",*e);
else if(*e == '(')
push(*e);
else if(*e == ')')
{
while((x = pop()) != '(')
printf("%c", x);
}
else
{
while(priority(stack[top]) >= priority(*e))
printf("%c",pop());
push(*e);
}
e++;
}

while(top != -1)
{
printf("%c",pop());
}
return 0;
}
int main()
{
char exp[100]="a+b*(c^d-e)^(f+g*h)-i"; IntoPost(exp);
return 1;
}

2
Output:

Result:
Thus, we have written a C program to implement conversion of Infix to Postfix expression.

3
Ex. No. 02 EVALUATION OF POSTFIX EXPRESSION
Date:

Aim:
To evaluate the post fix expression using Stack and also print the output of the given postfix expression inside the
function.

Algorithm:
1. Create a stack to store operands (or values).
2. Scan the given expression from left to right and do the following for every scanned element.
3. If the element is a number, push it into the stack
4. If the element is an operator, pop operands for the operator from the stack. Evaluate the operator and push
the result back to the stack
5. When the expression is ended, the number in the stack is the final answer

Program:
#include<stdio.h>
#include<ctype.h>

int stack[20];
int top = -1;

void push(int x)
{
stack[++top]=x;
}

int pop()
{
if(top==-1)
return -1;
return stack[top--];
}

void evalpostfix(char *e)


{
int n1,n2,n3,num;
while(*e!='\0')
{
if(isdigit(*e))
{
num=*e-48;

4
push(num);
}
else
{
n1= pop();
n2=pop();
switch(*e)
{
case '-': n3=n2-n1;
break;
case '*': n3=n2*n1;
break;
}
push(n3);
}
e++;
}
printf("%d",stack[top]);
}

int main()
{
char exp[20]="234*-6*";
evalpostfix(exp);
return 0;
}

Output:

Result:
Thus, the C function to evaluate the post fix expression using Stack for 234*-6* has been implemented successfully

5
Ex. No. 03 CIRCULAR QUEUE
Date:

Aim:
To develop the code to insert and delete elements in Circular Queue.

Algorithm:
Insert Operation:
1. Check if the queue is full.
2. For the first element, set value of FRONT to 0.
3. Circularly increase the REAR index by 1.
4. Add the new element in the position pointed to by REAR.
Delete Operation:
1. Check if the queue is empty.
2. Return the value pointed by FRONT.
3. Circularly increase the FRONT index by 1.
4. For the last element, reset the value of FRONT and REAR to -1.

Program:
#include<stdio.h>
#include<stdlib.h>
#define max 10
int insq(int cqueue[max], int *front, int *rear, int *data)
{
if((*rear + 1) % max == *front)
return(-1);
else
{
*rear = (*rear + 1) % max;
cqueue[*rear] = *data;
return(1);
}
}
int delq(int cqueue[max], int *front, int *rear, int *data)
{
if(*front == *rear)
return(-1);
else
{
*front = (*front + 1) % max;

6
*data = cqueue[*front];
return(1);
}
}

int main()
{
int cqueue[max], data;
int front, rear, reply,ch;
front = rear = 0; //... Initialize Circular Queue
printf(" ----------------------------\n”);
printf("\tMenu");
printf("\n------------------------------);
printf(“\n 1. Insert number in a Circular Queue”);
printf(“\n 1. Delete number in a Circular Queue”);
printf(“\n 3. Exit \n”);
printf(“--------------------------------\n);

while(1)
{
printf("Choose operation : ");
scanf("%d", &ch);
switch(ch)
{
case 1 : // insert
printf("\nEnter number: ");
scanf("%d", &data);
reply = insq(cqueue, &front, &rear, &data);
if(reply == -1)
printf("\nCircular Queue is Full \n");
else
printf("%d is inserted in a Circular Queue\n\n", data);
break;
case 2 : // delete
reply = delq(cqueue, &front, &rear,&data);
if(reply == -1)
printf("\n Circular Queue is Empty \n");
else
printf("\n %d is deleted from Circular Queue \n", data);
printf("\n");
break;
case 3 : exit(0);
default: printf("Invalid operation \n");
}
}
return 0;
}

7
Output:

Result:
Thus, a C program to insert and delete elements in circular queue is developed and executed successfully.

8
Ex. No. 04 PRIORITY QUEUE
Date:

Aim:
To write a C program to insert and delete element(s) into the priority queue satisfying the max-heap property.

Algorithm:
1. Create a function heapify() to heapify the elements in the Binary Tree if any changes are made.
2. Find the largest among root, left child, and right child, then recursively call the same function until the root
element matches the largest element.
3. Create a function insert() to insert an element into the tree, which takes an array and the number which is to
be inserted as input.
4. If the size of the array is zero, then this number will be the root, else append the number and call the
heapify function recursively to heapify the elements.
5. Create a function deleteNode() that deletes the selected element from the tree.
6. Delete the element and again heapify the elements recursively.
7. Insert elements into an empty array using the insert() function then try deleting an element from the tree.

Program:

#include <stdio.h>

int size = 0;

void swap(int *a, int *b)


{
int temp = *b;
*b = *a;
*a = temp;
}

// Function to heapify the tree


void heapify(int array[], int size, int i)
{
if (size == 1)
{
printf("Single element in the heap");
}
else
{
// Find the largest among root, left child and right child

9
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;
// Swap and continue heapifying if root is not largest
if (largest != i)
{
swap(&array[i], &array[largest]);
heapify(array, size, largest);
}
}
// Function to insert an element into the tree
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);
}
}
}

// Function to delete an element from the tree


void deleteRoot(int array[], int num)
{
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);
}
}

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

int main()
{
int m,k,e,r;
int array[10];
printf("Enter the number of elements to be inserted: ");
scanf("%d",&m);
printf("Enter the elements to be inserted:\n ");
for(k=0;k<m;k++)
{
scanf("%d",&e);
insert(array,e);
}
printf("Max-Heap array after insertion: ");
printArray(array, size);
printf("Enter the number of elements to be deleted: ");
scanf("%d",&m);
printf("Enter the elements to be deleted:\n ");
for(k=0;k<m;k++)
{
scanf("%d",&r);
deleteRoot(array, r);
}
printf("Max-Heap array after deletion: ");
printArray(array, size);
}

11
Output:

Insertion

Deletion

Result:

Thus, a C program to insert and delete element(s) into the priority queue is developed and executed
successfully.

12
Ex. No. 05 DEQUE DATA STRUCTURE
Date:

Aim:
To write a C program to insert and delete from both the ends in deQue.

Algorithm:
1. Take an array (deque) of size n and set two pointers at the first position and set front
= -1 and rear = 0.
2. Insert at the front.
This operation adds an element at the front.
• Check the position of front.
• If front < 1, reinitialize front = n-1 (last index).
• Else, decrease front by 1.
• Add the new key 5 into array[front].
3. Insert at the Rear.
This operation adds an element to the rear.
• Check if the array is full.
• If the deque is full, reinitialize rear = 0.
• Else, increase rear by 1.
• Add the new key 5 into array[rear].
4. Delete from the Front.
The operation deletes an element from the front.
• Check if the deque is empty.
• If the deque is empty (i.e. front = -1), deletion cannot be performed (underflow condition).
• If the deque has only one element (i.e. front = rear), set front = -1 and rear
• = -1.
• Else if front is at the end (i.e. front = n - 1), set go to the front front = 0.
• Else, front = front + 1.
5. Delete from the Rear
This operation deletes an element from the rear.
• Check if the deque is empty.
• If the deque is empty (i.e. front = -1), deletion cannot be performed (underflow condition).
• If the deque has only one element (i.e. front = rear), set front = -1 and rear = -1, else follow the
steps below.
• If rear is at the front (i.e. rear = 0), set go to the front rear = n - 1.
• Else, rear = rear - 1.

13
Program:
#include <stdio.h>
#define MAX 10
void addFront(int *, int, int *, int *);
void addRear(int *, int, int *, int *);
int delFront(int *, int *, int *);
int delRear(int *, int *, int *);
void display(int *);
int count(int *);

int main()
{
int arr[MAX];
int front, rear, i, n;
front = rear = -1;

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


arr[i] = 0;

addRear(arr, 5, &front, &rear);


addFront(arr, 12, &front, &rear);
addRear(arr, 11, &front, &rear);
addFront(arr, 5, &front, &rear);
addRear(arr, 6, &front, &rear);
addFront(arr, 8, &front, &rear);

printf("\nElements in a deque: ");


display(arr);

i = delFront(arr, &front, &rear);


printf("\nremoved item: %d", i);
printf("\nElements in a deque after deletion: ");
display(arr);

addRear(arr, 16, &front, &rear);


addRear(arr, 7, &front, &rear);

printf("\nElements in a deque after addition: ");


display(arr);

i = delRear(arr, &front, &rear);


printf("\nremoved item: %d", i);
printf("\nElements in a deque after deletion: ");
display(arr);

n = count(arr);
printf("\nTotal number of elements in deque: %d", n);

14
}

// Insertion At Front
void addFront(int *arr, int item, int *pfront, int *prear)
{
int i, k, c;
if (*pfront == 0 && *prear == MAX - 1)
{
printf("\nDeque is full.\n");
return;
}
if (*pfront == -1)
{
*pfront = *prear = 0; arr[*pfront] = item;
return;
}
if (*prear != MAX - 1)
{
c = count(arr);
k = *prear + 1;
for (i = 1; i <= c; i++)
{
arr[k] = arr[k - 1];
k--;
}
arr[k] = item;
*pfront = k;
(*prear)++;
}
else
{
(*pfront)--;
arr[*pfront] = item;
}
}

// Insertion At Rear
void addRear(int *arr, int item, int *pfront, int *prear)
{
int i, k;
if (*pfront == 0 && *prear == MAX - 1)
{
printf("\nDeque is full.\n");
return;
}
if (*pfront == -1)
{
*prear = *pfront = 0;
arr[*prear] = item;

15
return;
}
if (*prear == MAX - 1)
{
k = *pfront - 1;
for (i = *pfront - 1; i < *prear; i++)
{
k = i;
if (k == MAX - 1)
arr[k] = 0;
else
arr[k] = arr[i + 1];
}
(*prear)--;
(*pfront)--;
}
(*prear)++;
arr[*prear]= item;
}

// Deletion At Front
int delFront(int *arr, int *pfront, int *prear)
{
int item;
if (*pfront == -1)
{
printf("\nDeque is empty.\n");
return 0;
}
item = arr[*pfront];
arr[*pfront] = 0;
if (*pfront == *prear)
*pfront = *prear = -1;
else
(*pfront)++;
return item;
}

// Insertion At Rear
int delRear(int *arr, int *pfront, int *prear)
{
int item;
if (*pfront == -1)
{
printf("\nDeque is empty.\n");
return 0;
}
item = arr[*prear];
arr[*prear] = 0;

16
(*prear)--;
if (*prear == -1)
*pfront = -1;
return item;
}

// Display the output


void display(int *arr)
{
int i;
printf("\n front: ");
for (i = 0; i < MAX; i++)
printf(" %d", arr[i]);
printf(" :rear");
}

int count(int *arr)


{
int c = 0, i;
for (i = 0; i < MAX; i++)
{
if (arr[i] != 0) c++;
}
return c;
}

17
Output:
Insert at the front:

Insert at the rear:

Delete at the front:

Delete at the rear:

Result:
Thus, a C program to insert and delete from both the ends in deque is developed and executed successfully.

18
Ex. No. 06 BINARY TREE
Date:

Aim:
To write a C program to insert and delete elements in Binary tree.

Algorithm:
1. Declare a structure of node.
2. In order to insert any node, create a node as it contains data and declare left and right child as null.
3. If the new node is the first node to insert, then it is the root node.
4. If it is lesser than the root node’s data, then it is linked with left child.
5. If it is greater than the root node’s data, then it is linked with right child.
6. In deletion, the delete operation is done at leaf node. First ,it goes with left and delete all data. Similarly, it
goes with right and delete all data.
7. Finally, it delete the root node.

Program:
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

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

struct node* insert( struct node* root, int data )


{
if(root == NULL)
{
struct node* node = (struct node*)malloc(sizeof (struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return node;
}
else
{
struct node* cur;

19
if(data <= root->data)
{
cur = insert(root->left, data);
root->left = cur;
}
else
{
cur = insert(root->right, data);
root->right = cur;
}
return root;
}
}

void display(struct node *root)


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

void delete_tree(struct node *root)


{
if(root==NULL)
{
return;
}
delete_tree(root->left);
delete_tree(root->right);
free(root);
}

int main()
{
struct node* root = NULL;
int t;
int data,choice=2;
scanf("%d", &t);

while(t-- > 0)
{
scanf("%d", &data);
root = insert(root, data);
}
switch(choice)
{
case 1:

20
display(root);
break;
case 2:
delete_tree(root);
printf("Deleted successfully");
break;
}
return 0;
}

Output:

Result:
Thus, C program to insert and delete elements in Binary tree is implemented.

21
Ex. No. 07 BINARY SEARCH TREE
Date:

Aim:
To write the c program to insert and delete element in binary search tree.

Algorithm:
1. Import the necessary header files.
2. Define the maximum size of the tree and declare the variables and functions.
3. In the main function call btnode function to create the tree nodes.
4. The nodes have two values left node and right node.
5. The higher value placed in right side node and lower value is placed in left side node.
6. In the insert function check the nodes values higher or lower .if the lower to head node insert the node in
left side otherwise insert in right side.
7. In Deletion operation check the four cases.
8. Case1: If the node to be deleted is the leaf node. In such a case, simply delete the node from the tree.
9. Case 2: In the second case, the node to be deleted lies has a single child node. In such a case follow the steps
below:
• Replace that node with its child node.
• Remove the child node from its original position.
10. Case 3:In the third case, the node to be deleted has two children. In such a case follow the steps below:
• Get the inorder successor of that node.
• Replace the node with the inorder successor.
• Remove the inorder successor from its original position.

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

struct btnode
{
int value;
struct btnode *l;
struct btnode *r;
}*root = NULL, *temp = NULL, *t2, *t1;

void delete1();
struct btnode *insert(struct btnode *root,int data);
void delete(struct btnode *root);
void inorder(struct btnode *t);
void create();

22
struct btnode *search(struct btnode *t);
void search1(struct btnode *t,int data);
int smallest(struct btnode *t);
int largest(struct btnode *t);
int flag = 1;

int main()
{
int n,data;
struct btnode *root = NULL;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&data);
root = insert(root, data);
}
delete(root);
inorder(root);
return 0;
}

/* To insert a node in the tree */


struct btnode insert(struct btnode root,int data)
{
temp = (struct btnode *)malloc(1*sizeof(struct btnode));
temp->value = data;
temp->l = temp->r = NULL;
if (root == NULL)
root = temp;
else
root=search(root);
return root;
}

/* Function to search the appropriate position to insert the new node */


struct btnode *search(struct btnode *t)
{
if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node value insert at right */
search(t->r);
else if ((temp->value > t->value) && (t->r == NULL))
t->r = temp;
else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value insert at left */
search(t->l);
else if ((temp->value < t->value) && (t->l == NULL))
t->l = temp;
return t;
}

/* recursive function to perform inorder traversal of tree */

23
void inorder(struct btnode *t)
{
if (t)
{
inorder(t->l);
printf("%d -> ", t->value);
inorder(t->r);
}
}

/* To check for the deleted node */


void delete(struct btnode *root)
{
int data;
/*if (root == NULL)
{
printf("No elements in a tree to delete");
return;
}*/
//printf("Enter the data to be deleted : ");
scanf("%d",&data);
t1 = root;
t2 = root;
search1(root,data);
}

/* Search for the appropriate position to insert the new node */


void search1(struct btnode *t, int data)
{
if ((data>t->value))
{
t1 = t;
search1(t->r,data);
}
else if ((data < t->value))
{
t1 = t;
search1(t->l,data);
}
else if ((data==t->value))
{
delete1(t);
}
}

int smallest(struct btnode *t)


{
t2 = t;
if (t->l != NULL)

24
{
t2 = t;
return(smallest(t->l));
}
else
return (t->value);
}

/* To find the largest element in the left sub tree */


int largest(struct btnode *t)
{
if (t->r != NULL)
{
t2 = t;
return(largest(t->r));
}
else
return(t->value);
}

void delete1(struct btnode *t)


{
int k;
/* To delete leaf node */
if ((t->l == NULL) && (t->r == NULL))
{
if (t1->l == t)
{
t1->l = NULL;
}
else
{
t1->r = NULL;
}
t = NULL;
free(t);
return;
}
/* To delete node having one left hand child */
else if ((t->r == NULL))
{
if (t1 == t)
{
root = t->l;
t1 = root;
}
else if (t1->l == t)
{
t1->l = t->l;

25
}
else
{
t1->r = t->l;
}
t = NULL;
free(t);
return;
}
/* To delete node having right hand child */
else if (t->l == NULL)
{
if (t1 == t)
{
root = t->r;
t1 = root;
}
else if (t1->r == t)
t1->r = t->r;
else
t1->l = t->r;
//t == NULL;
free(t);
return;
}
/* To delete node having two child */
else if ((t->l != NULL) && (t->r != NULL))
{
t2 = root;
if (t->r != NULL)
{
k = smallest(t->r);
flag = 1;
}
else
{
k =largest(t->l);
flag = 2;
}
search1(root, k);
t->value = k;
}
}

26
Output:

Insertion:

Deletion:

Result:
Hence, we have successfully implemented a code to determine a binary search tree insertion and deletion.

27
Ex. No. 08 AVL TREE
Date:

Aim:
To Write a C program to insert and delete elements in AVL tree.

Algorithm:
Insertion:
1. Create the appropriate empty subtree where the new value should be added by comparing the values in the
tree.
2. Create a new node at the empty subtree.
3. The new node is a leaf ad thus will have a balance factor of zero.
4. Return to the parent node and adjust the balance factor of each node through the rotation process and
continue it until we are back at the root. Remember that the modification of the balance factor must happen
in a bottom-up fashion.
Deletion:
1. Locate the node to be deleted.
2. If the node does not have any child, then remove the node.
3. If the node has one child node, replace the content of the deletion node with the child node and remove the
node.
4. If the node has two children’s nodes, find the inorder successor node ‘k’ which has no child node and
replace the contents of the deletion node with the ‘k’ followed by removing the node.
5. Update the balance factor of the AVL tree.

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

// Create Node
struct Node
{
int key;
struct Node *left;
struct Node *right;
int height;
};

int max(int a, int b);


// Calculate height
int height(struct Node *N)

28
{
if (N == NULL)
return 0;
return N->height;
}

int max(int a, int b)


{
return (a > b) ? a : b;
}

// Create a node
struct Node *newNode(int key)
{
struct Node *node = (struct Node *)
malloc(sizeof(struct Node));
node->key = key;
node->left = NULL;
node->right = NULL;
node->height = 1;
return (node);
}

// Right rotate
struct Node *rightRotate(struct Node *y)
{
struct Node *x = y->left;
struct Node *T2 = x->right;

x->right = y;
y->left = T2;

y->height = max(height(y->left), height(y->right)) + 1;


x->height = max(height(x->left), height(x->right)) + 1;

return x;
}

// Left rotate
struct Node *leftRotate(struct Node *x)
{
struct Node *y = x->right;
struct Node *T2 = y->left;

y->left = x;
x->right = T2;

x->height = max(height(x->left), height(x->right)) + 1;


y->height = max(height(y->left), height(y->right)) + 1;

29
return y;
}

// Get the balance factor


int getBalance(struct Node *N)
{
if (N == NULL)
return 0;
return height(N->left) - height(N->right);
}

// Insert node
struct Node *insertNode(struct Node *node, int key)
{
// Find the correct position to insertNode the node and insertNode it
if (node == NULL)
return (newNode(key));

if (key < node->key)


node->left = insertNode(node->left, key);
else if (key > node->key)
node->right = insertNode(node->right, key);
else
return node;

// Update the balance factor of each node and


// Balance the tree
node->height = 1 + max(height(node->left),
height(node->right));

int balance = getBalance(node);


if (balance > 1 && key < node->left->key)
return rightRotate(node);

if (balance < -1 && key > node->right->key)


return leftRotate(node);

if (balance > 1 && key > node->left->key)


{
node->left = leftRotate(node->left);
return rightRotate(node);
}

if (balance < -1 && key < node->right->key)


{
node->right = rightRotate(node->right);
return leftRotate(node);
}

30
return node;
}

struct Node *minValueNode(struct Node *node)


{
struct Node *current = node;

while (current->left != NULL)


current = current->left;

return current;
}

// Delete a nodes
struct Node *deleteNode(struct Node *root, int key)
{
// Find the node and delete it
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) || (root->right == NULL))
{
struct Node *temp = root->left ? root->left : root->right;
if (temp == NULL)
{
temp = root;
root = NULL;
}
else
*root = *temp;
free(temp);
}
else
{
struct Node *temp = minValueNode(root->right);
root->key = temp->key;

root->right = deleteNode(root->right, temp->key);


}
}

31
if (root == NULL)
return root;

// Update the balance factor of each node and


// balance the tree
root->height = 1 + max(height(root->left),
height(root->right));

int balance = getBalance(root);


if (balance > 1 && getBalance(root->left) >= 0)
return rightRotate(root);

if (balance > 1 && getBalance(root->left) < 0)


{
root->left = leftRotate(root->left);
return rightRotate(root);
}

if (balance < -1 && getBalance(root->right) <= 0)


return leftRotate(root);

if (balance < -1 && getBalance(root->right) > 0)


{
root->right = rightRotate(root->right);
return leftRotate(root);
}

return root;
}

// Print the tree


void printPreOrder(struct Node *root)
{
if (root != NULL)
{
printf("%d ", root->key);
printPreOrder(root->left);
printPreOrder(root->right);
}
}

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

root = insertNode(root, 2);


root = insertNode(root, 1);
root = insertNode(root, 7);

32
root = insertNode(root, 4);
root = insertNode(root, 5);
root = insertNode(root, 3);
root = insertNode(root, 8);

printPreOrder(root);

root = deleteNode(root, 3);

printf("\nAfter deletion: ");


printPreOrder(root);

return 0;
}

Output:

Result:
Thus, C program to insert and delete elements in AVL tree implemented successfully.

33
Ex. No. 09 B TREE
Date:

Aim:
To write a C program to insert elements in B tree.

Algorithm:
1. If the tree is empty, allocate a root node and insert the key.
2. Update the allowed number of keys in the node.
3. Search the appropriate node for insertion.
4. If the node is full, follow the steps below.
5. Insert the elements in increasing order.
6. Now, there are elements greater than its limit. So, split at the median.
7. Push the median key upwards and make the left keys as a left child and the right keys as a right child.
8. If the node is not full, follow the steps below.
9. Insert the node in increasing order.

Program:
#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;
}

34
// 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));


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

35
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;
}

// 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);
}

36
// 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 n,x;
scanf("%d",&n);
for(int i=0;i<n;i++)
{
scanf("%d",&x);
insert(x);
}
traversal(root);
}

37
Output:

Result:
Thus, the C program to insert elements in B tree has been implemented successfully.

38
Ex. No. 10 BREADTH FIRST SEARCH
Date:

Aim:
To write a C program to implement breadth first search.

Algorithm:
1. Ready state for each node in G
2. Enqueue the starting node A and set its waiting state Repeat Steps 4 and 5 until Queue is empty.
3. Dequeue a node N. Process it and set its processed state.
4. Enqueue all the neighbours of N that are in the ready state and set waiting state.
5. Stop.

Program:

#include<stdio.h>

void BFS(int);
int graph[10][10], visited[10],total = 5;

main()
{
int i,j;
printf("\nEnter the total number of vertices in graph\n");
scanf("%d",&total);

/*Adjacency matrix input*/


printf("\nEnter the adjacency matrix\n");
for(i=0;i<total;i++)
{
for(j=0;j<total;j++)
{
scanf("%d",&graph[i][j]);
}
}

for(i=0;i<total;i++)
{
visited[i] = 0;
}
printf("\nBFS traversal is \n");

39
BFS(0);
}
void BFS(int vertex)
{
int queue[total], rear=-1, front=-1, j;
queue[++rear] = vertex;
front++;
visited[vertex] = 1;
while(front<=rear)
{
vertex = queue[front++];
printf("%d\t",vertex);
for(j=0;j<total;j++)
{
if(!visited[j] && graph[vertex][j] == 1 )
{
queue[++rear] = j;
visited[j] = 1;
}
}
}
}

Output:

Result:
Thus, the c program to traverse the graph using Breadth first search has been implemented successfully.

40
Ex. No. 11 DEPTH FIRST SEARCH
Date:

Aim:
To write a C program to implement depth first search.

Algorithm:
1. Start by putting any one of the graph’s vertices on top of a stack.
2. Take the top item of the stack and add it to the visited list.
3. Create a list of that vertex’s adjacent nodes. Add the ones which aren’t in the visited list to the top of the
stack.
4. Keep repeating steps 2 and 3 until the stack is empty.

Program:

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

int graph[10][10], visited[10],total,arr[30];


static int k=0,count=0;
void DFS(int);
int main()
{
int i,j;
printf("\nEnter the total number of vertices in graph\n");
scanf("%d",&total);
/*Adjacency matrix input*/
printf("\nEnter the adjacency matrix\n");
for(i=0;i<total;i++)
{
for(j=0;j<total;j++)
{
scanf("%d",&graph[i][j]);
}
}
for(i=0;i<total;i++)
{
visited[i] = 0;
}
printf("\nDFS traversal is \n");
DFS(0);

41
return 0;
}
void DFS(int vertex)
{
int j,c=0;
count++;
printf("%d\t",vertex);
visited[vertex] = 1;
for(j=0;j<total;j++)
{
if(!visited[j] && graph[vertex][j] == 1)
{
arr[++k] = j;
c=1;
}
if(count == total)
{
exit(0);
}
}
if(c==1)
{
DFS(arr[k]);
}
else
{
k--;
DFS(arr[k]);
}
}

42
Output:

Result:
Thus, the c program to traverse the graph using depth first search has been implemented successfully.

43
Ex. No. 12 TOPOLOGICAL SORT
Date:

Aim:
Incorporate the check in the code to determine a cyclic graph which aborts the topological ordering of the graph
shown below.

Algorithm:
1. Import the necessary header files.
2. Define the maximum size and declare the other global variables and functions.
3. Within the main function, call the create_graph function to create the graph.
4. Using a for loop, iterate over the vertexes, and insert them into the queue using insert_queue.
5. Define a while loop and add the vertex ‘v’ the topo_order array. Also, delete all the edges going from vertex
‘v’.
6. Use an if condition to check topological ordering. And print the topological order if valid.

Program:

#include<stdio.h>
#include<stdlib.h>
#define MAX 5

int n;
int adj[MAX][MAX];
void create_graph();
int queue[MAX], front = -1, rear = -1;
void insert_queue(int v);
int delete_queue();
int isEmpty_queue();
int indegree(int v);

44
void create_graph()
{
int i, max_edges, origin, destin;
scanf("%d", & n);
max_edges = n * (n - 1);
for (i = 1; i <= max_edges; i++)
{
scanf("%d %d", & origin, & destin);
if ((origin == -1) && (destin == -1))
break;
if (origin >= n || destin >= n || origin < 0 || destin < 0)
{
printf("Invalid edge!\n");
i--;
}
else
adj[origin][destin] = 1;
}
}

int indegree(int v)
{
int i, in_deg = 0;
for (i = 0; i < n; i++)
{
if (adj[i][v] == 1)
{
in_deg++;
return in_deg;
}
}
}

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

45
int isEmpty_queue()
{
if (front == -1 || front > rear)
return 1;
else
return 0;
}

void insert_queue(int vertex)


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

int main()
{
int i, v, count, topo_order[MAX], indeg[MAX];
create_graph();
for (i = 0; i < n; i++)
{
indeg[i] = indegree(i);
if (indeg[i] == 0)
insert_queue(i);
}
count = 0;
while (!isEmpty_queue() && count < n)
{
v = delete_queue();
topo_order[++count] = v;
for (i = 0; i < n; i++)
{
if (adj[v][i] == 1)
{
adj[v][i] = 0;
indeg[i] = indeg[i] - 1;
if (indeg[i] == 0)
insert_queue(i);
}
}
}
if (count < n)

46
{
printf("No topological ordering possible, graph contains cycle\n");
exit(1);
}
printf("Vertices in topological order are :\n");
for (i = 1; i <= count; i++)
printf("%d ", topo_order[i]); printf("\n");
return 0;
}

Output:

Result:
Hence, we have successfully implemented a code to determine a cyclic graph which aborts the topological ordering
for the given graph.

47
Ex. No. 13 PRIM’S ALGORITHM
Date:

Aim:
Write a C Program to implement Prim's Algorithm for finding Total Cost of spanning tree.

Algorithm:
1. Start the program
2. Initialize the minimum spanning tree with a vertex chosen at random.
3. Find all the edges that connect the tree to new vertices, find the minimum and add it to the tree .
4. Keep repeating step 2 until we get a minimum spanning tree.
5. Stop the program.

Program:

#include<stdio.h>
#include<stdlib.h>
#define infinity 9999
#define MAX 20

int G[MAX][MAX],spanning[MAX][MAX],n;
int prims(); int main()

{
int i,j,total_cost;
scanf("%d",&n);
for(i=0;i<n;i++) for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
total_cost=prims();
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
printf("%d ",spanning[i][j]);
printf("\n");
}
printf("\nTotal cost of spanning tree=%d",total_cost);
return 0;
}

48
int prims()
{
int cost[MAX][MAX];
int u,v,min_distance,distance[MAX],from[MAX];
int visited[MAX],no_of_edges,i,min_cost,j;
for(i=0;i<n;i++)
for(j=0;j<n;j++)
{
if(G[i][j]==0)
cost[i][j]=infinity;
else
cost[i][j]=G[i][j];
spanning[i][j]=0;
}
visited[0]=1;
for(i=1;i<n;i++)
{
distance[i]=cost[0][i];
from[i]=0;
visited[i]=0;
}
min_cost=0; //cost of spanning tree no_of_edges=n-1;
//no. of edges to be added
while(no_of_edges>0)
{
for(i=1;i<n;i++)
if(visited[i]==0&&distance[i]<min_distance)
{
v=i; min_distance=distance[i];
}
u=from[v];
//insert the edge in spanning tree
spanning[u][v]=distance[v];
spanning[v][u]=distance[v];
no_of_edges--;
visited[v]=1;
//updated the distance[] array
for(i=1;i<n;i++)
if(visited[i]==0&&cost[i][v]<distance[i])
{
distance[i]=cost[i][v];
from[i]=v;
}
min_cost=min_cost+cost[u][v];
}
return(min_cost);
}

49
Output:

Result:

Thus, the C program for Prim's Algorithm to finding Total Cost of spanning tree has been implemented
successfully

50
Ex. No. 14 KRUSKAL’S ALGORITHM
Date:

Aim:
To write a C program to implement Kruskal’s algorithm for finding minimum cost.

Algorithm:
1. Start
2. Sort all edges in increasing order of their edge weights.
3. Pick the smallest edge.
4. Check if the new edge creates a cycle or loop in a spanning tree.
5. If it doesn’t form the cycle, then include that edge in MST. Otherwise, discard it.
6. Repeat from step 2 until it includes |V| - 1 edges in MST.
7. Stop

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

int i,j,k,a,b,u,v,n,ne=1;
int min,mincost=0,cost[9][9],parent[9];
int find(int);
int uni(int,int);

int main()
{
scanf("%d",&n);
for(i=1;i<=n;i++)
{
for(j=1;j<=n;j++)
{
scanf("%d",&cost[i][j]);
if(cost[i][j]==0)
cost[i][j]=999;
}
}
while(ne < n)
{
for(i=1,min=999;i<=n;i++)
{
for(j=1;j <= n;j++)
{

51
if(cost[i][j] < min)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
}
}
u=find(u);
v=find(v);
if(uni(u,v))
{
printf("%d edge (%d,%d) =%d\n",ne++,a,b,min);
mincost +=min;
}
cost[a][b]=cost[b][a]=999;
}
printf("Minimum cost = %d\n",mincost); return 0;
}

int find(int i)
{
while(parent[i])
i=parent[i];
return i;
}

int uni(int i,int j)


{
if(i!=j)
{
parent[j]=i;
return 1;
}
return 0;
}

52
Output:

Result:
Thus, we have written a C program to implement Kruskal’s algorithm for finding minimum cost.

53
Ex. No. 15 TRAVELLING SALESMAN PROBLEM
Date:

Aim:
To write a C program to implement the travelling salesman problem.

Algorithm:
1. Start
2. First of all, we have to create two primary data holders.
3. First of them is a list that can hold the indices of the cities in terms of the input matrix of distances between
cities.
4. And the Second one is the array which is our result.
5. Perform traversal on the given adjacency matrix tsp[][] for all the city and if the cost of reaching any city
from the current city is less than the current cost the update the cost.
6. Generate the minimum path cycle using the above step and return their minimum cost.
7. Stop

Program:

#include<stdio.h>

int ary[10][10],completed[10],n,cost=0;

void takeInput()
{
int i,j;
scanf("%d",&n);
for(i=0;i < n;i++)
{
for( j=0;j < n;j++)
scanf("%d",&ary[i][j]);
completed[i]=0;
}
}

void mincost(int city)


{
int ncity;
int least(int);
completed[city]=1;
printf("%d--->",city+1);
ncity=least(city);

54
if(ncity==999)
{
ncity=0;
printf("%d",ncity+1);
cost+=ary[city][ncity];
return;
}
mincost(ncity);
}

int least(int c)
{
int i,nc=999;
int min=999,kmin;
for(i=0;i < n;i++)
{
if((ary[c][i]!=0)&&(completed[i]==0))
if(ary[c][i]+ary[i][c] < min)
{
min=ary[i][0]+ary[c][i];
kmin=ary[c][i];
nc=i;
}
}
if(min!=999) cost+=kmin;
return nc;
}

int main()
{
takeInput();
mincost(0); //passing 0 because starting vertex
printf("\n\nMinimum cost is %d\n ",cost);
return 0;
}

55
Output:

Result:
Thus, the travelling salesman problem was implemented successfully.

56

You might also like