You are on page 1of 70

CSE2003 – DATA STRUCTURES & ALGORITHMS

L31-L32

LAB RECORD

Submitted to

Dr. RAJALAKSHMI R
SCHOOL OF ELECTRONICS ENGINEERING

MARCH 2019

P.R. KAAVIYA

17BEC1006

1
INDEX PAGE

CONTENT PAGE
DATE MARKS
NO

LAB 1 10.12.18 10 3

LAB 2 17.12.18 8 10

LAB 3 07.01.19 9 17

LAB 4 21.01.19 10 25

LAB 5 4.02.19 10 + 5 30

LAB 6 9.02.19 10+5 40

LAB 7 11.02.19 10 46

LAB 8 18.02.19 10 53

LAB 9 25.02.19 10 55

LAB 10 11.03.18 10 60

LAB 11 18.03.19 10 66

2
LAB EXERCISE 1.1
10.12.18

ARRAY IMPLEMENTATION OF STACKS

1. PSEUDOCODE & ALGORITHM:


int stack[100],n,top,x,i;
void push()
{ if (top>=n-1)
printf("\nStack Overflow --> Stack is full");
else
scanf("%d", &x);
top++;
stack[top]=x;}
void display()
{if(top>=0)
for (i=top;i>=0;--i)
printf(" %d " ,stack[i]); }
void pop()
{ if (top<=-1)
printf("\nStack Underflow --> Stack is empty");
else
top--;}

2. PROGRAM CODE:
#include<stdio.h>
void push(void);
void pop(void);
void display(void);
int stack[50],choice,n,top,p,i;
int main()
{
//clrscr();
top=-1;
printf("\nEnter the size (<50): ");
scanf("%d",&n);
do
{
printf("\n\nWhich operation would you like to perform?");
printf("\n1. PUSH") ;
printf("\n2. POP") ;
printf("\n3. DISPLAY") ;
printf("\n4. EXIT") ;
printf("\nENTER CHOICE : ") ;
scanf("%d",&choice);
switch(choice)
{
case 1:
{
printf("\nPushing an element -") ;
push();
break;
}
case 2:
{
printf("\nPopping an element - ") ;
pop();
break;
}
case 3:

3
{
printf("\nDisplaying the stack - ") ;
display();
break;
}
case 4:
{
printf("\n\t Exit");
break;
}
default:
{
printf ("\n\t** Please Enter a Valid Choice(1:4) **");
}
}
}
while(choice!=4);
return 0;
}
void push()
{
if(top>=n-1)
{
printf("\n\t** MESSAGE : STACK OVERFLOW **\n");
}
else
{
printf("\nEnter a value to be pushed : ");
scanf("%d",&p);
top++;
stack[top]=p;
}
}
void pop()
{
if(top<=-1)
{
printf("\n\t** MESSAGE : STACK UNDERFLOW **\n");
}
else
{
printf("\n\tThe popped elements is : %d",stack[top]);
top--;
}
}
void display()
{
if(top>=0)
{
printf("\nElements in the stack from top to bottom are : \n");
for(i=top; i>=0; i--)
printf("\n%d",stack[i]);
}
else
{
printf("\n\t** MESSAGE : STACK IS EMPTY **\n");
}
}

4
3. OUTPUT

5
4. VERIFICATION

6
LAB EXERCISE 1.2
10.12.18

ARRAY IMPLEMENTATION OF QUEUE

1. PSEUDOCODE & ALGORITHM:


int queue[100],choice,n,front,rear,x,i; //array name is stack, it can
void enqueue()
{if (rear>=n-1)
printf("\nQueue Overflow --> Queue is full");
else
scanf("%d", &x);
rear=rear+1;
queue[rear]=x; }
void display()
{if(rear<0)
printf("The queue is Empty");
else if (rear>=0)
for (i=front+1;i<=rear;i++)
printf(" %d " ,queue[i]);}
void dequeue()
{if (front==rear)
printf("\nQueue Underflow --> Queue is empty");
else
front=front+1; }

2. PROGRAM CODE:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int queue[100], n = 100, front = - 1, rear = - 1;
void Insert() {
int val;
if (rear == n - 1)
cout<<"Queue Overflow!"<<endl;
else {
if (front == - 1)
front = 0;
cout<<"Insert the element in queue : ";
cin>>val;
rear++;
queue[rear] = val;
}
}
void Delete() {
if (front == - 1 || front > rear) {
cout<<"Queue Underflow!"<<endl;
return ;
} else {
cout<<"Element deleted from queue is : "<< queue[front] << endl;
front++;;
}
}
void Display() {
if (front == - 1)
cout<<"Queue is empty!"<<endl;
else {
cout<<"Queue elements are : ";
for (int i = front; i <= rear; i++)

7
cout<<queue[i]<<" ";
cout<<endl;
}
}
int main() {
int ch;
cout<<"1) Insert element to queue"<<endl;
cout<<"2) Delete element from queue"<<endl;
cout<<"3) Display all the elements of queue"<<endl;
cout<<"4) Exit"<<endl;
do {
cout<<"Enter your choice : ";
cin>>ch;
switch (ch) {
case 1: Insert();
break;
case 2: Delete();
break;
case 3: Display();
break;
case 4: cout<<"Exit"<<endl;
break;
default: cout<<"Invalid choice"<<endl;
}
} while(ch!=4);
return 0;
}

3. OUTPUT

8
4. VERIFICATION

5. RESULT: Thus, stacks and queues were implemented using arrays.

9
LAB EXERCISE 2
17.12.18

IMPLEMENTATION OF SINGLY LINKED LIST

1. PSEUDOCODE & ALGORITHM:

Algorithm for traversing a singly linked list:


Step 1: [INITIALIZE] SET PTR = START
Step 2: Repeat Steps 3 and 4 while PTR != NULL
Step 3: Apply Process to PTR DATA
Step 4: SET PTR = PTR NEXT
[END OF LOOP]
Step 5: EXIT
Algorithm to search in a singly linked list:
Step 1: [INITIALIZE] SET PTR = START
Step 2: Repeat Step 3 while PTR != NULL
Step 3: IF VAL = PTR DATA
SET POS = PTR
Go To Step 5
ELSE
SET PTR = PTR NEXT
[END OF IF]
[END OF LOOP]
Step 4: SET POS = NULL
Step 5: EXIT
Algorithm to insert a new node at the beginning:
Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 7
[END OF IF]
Step 2: SET NEW_NODE = AVAIL
Step 3: SET AVAIL = AVAIL NEXT
Step 4: SET DATA = VAL
Step 5: SET NEW_NODE NEXT = START
Step 6: SET START = NEW_NODE
Step 7: EXIT
Algorithm to insert a new node at the end:
Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 1
[END OF IF]
Step 2: SET = AVAIL
Step 3: SET AVAIL = AVAIL NEXT
Step 4: SET DATA = VAL
Step 5: SET NEW_NODE = NULL
Step 6: SET PTR = START
Step 7: Repeat Step 8 while PTR NEXT != NULL
Step 8: SET PTR = PTR NEXT
[END OF LOOP]
Step 9: SET PTR NEXT = NEW NODE
Step 10: EXIT
Algorithm to insert a new node after a node that has value NUM:
Step 1: IF AVAIL = NULL
Write OVERFLOW
Go to Step 12
[END OF IF]
Step 2: SET = AVAIL
Step 3: SET AVAIL = AVAIL NEXT
Step 4: SET DATA = VAL
Step 5: SET PTR = START

10
Step 6: SET PREPTR = PTR
Step 7: Repeat Steps 8 and 9 while!= NUM
Step 8: SET PREPTR = PTR
Step 9: SET PTR = PTR NEXT
[END OF LOOP]
Step 10 : PREPTR NEXT =
Step 11: SET NEW_NODE NEXT = PTR
Step 12: EXIT
Algorithm to delete the first node:
Step 1: IF START = NULL
Write UNDERFLOW
Go to Step 5
[END OF IF]
Step 2: SET PTR = START
Step 3: SET START = START NEXT
Step 4: FREE PTR
Step 5: EXIT
Algorithm to delete the last node:
Step 1: IF START = NULL
Write UNDERFLOW
Go to Step 8
[END OF IF]
Step 2: SET PTR = START
Step 3: Repeat Steps 4 and 5 while PTR NEXT != NULL
Step 4: SET PREPTR = PTR
tep 5: SET PTR = PTR NEXT
[END OF LOOP]
Step 6: SET PREPTR-> NEXT = NULL
Step 7: FREE PTR
Step 8: EXIT
Algorithm to delete the node after a given node:
Step 1: IF START = NULL
Write UNDERFLOW
Go to Step 1
[END OF IF]
Step 2: SET PTR = START
Step 3: SET PREPTR = PTR
Step 4: Repeat Steps 5 and 6 while PREPTR DATA != NUM
Step 5: SET PREPTR = PTR
Step 6: SET PTR = PTR-> NEXT
[END OF LOOP]
Step 7: SET TEMP = PTR
Step 8: SET PREPTR-> NEXT = PTR-> NEXT
Step 9: FREE TEMP
Step 10: EXIT

2. PROGRAM CODE:
#include<stdio.h>
int ch;
struct node
{
int data;
struct node *next;
};
struct node *head;
void beginsert ();
void lastinsert ();
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void main()
{
printf("Choose an option from the list: ");
printf("\n1. Insert in beginning \n2. Insert in the end \n3. Insert at any location \n4. Delete from beginning \n5. Delete
from end \n6. Delete from anywhere \n7. Display \n8. Exit\n");

11
do{
scanf("%d",&ch);
switch(ch)
{
case 1:
{
beginsert();
break;
}
case 2:
{
lastinsert();
break;
}
case 3:
{
randominsert();
break;
}
case 4:
{
begin_delete();
break;
}
case 5:
{
last_delete();
break;
}
case 6:
{
random_delete();
break;
}
case 7:
{
display();
break;
}
case 8:
{
printf("\nExiting program\n");
break;
}
default:
{
printf("\nChoose correct option\n");
break;
}
}
printf("\nEnter choice: ");
}while(ch!=8);
}
void beginsert()
{
struct node *ptr;
int item;
ptr=(struct node *)malloc(sizeof(struct node *));
if(ptr==NULL)
{
printf("\nOverflow");
}
else
{
printf("\nEnter value: ");
scanf("%d",&item);
ptr->data=item;
ptr->next=head;
head=ptr;

12
}
}
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr=(struct node *)malloc(sizeof(struct node *));
if(ptr==NULL)
{
printf("\nOverflow");
}
else
{
printf("\nEnter value: ");
scanf("%d",&item);
ptr->data=item;
if(head==NULL)
{
ptr->next=NULL;
head=ptr;
}
else
{
temp=head;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=ptr;
ptr->next=NULL;
}
}
}
void randominsert()
{
int i,loc,item;
struct node *ptr,*temp;
ptr = (struct node*)malloc(sizeof(struct node));
if(ptr==NULL)
{
printf("\nOverflow");
}
else
{
printf("\nEnter value: ");
scanf("%d",&item);
ptr->data=item;
printf("\nEnter the value after which element must be inserted: ");
scanf("%d",&loc);
temp=head;
while(temp->next!=NULL)
{
if (temp->data==loc)
break;
else
printf("\nCant insert");
temp=temp->next;
}
ptr->next=temp->next;
temp->next=ptr;
}
}
void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nList is empty\n");
}

13
else
{
ptr = head;
head = ptr->next;
free(ptr);
printf("\nNode deleted from the begining\n");
}
}
void last_delete()
{
struct node *ptr,*ptr1;
if(head == NULL)
{
printf("\nlist is empty");
}
else if(head -> next == NULL)
{
head = NULL;
free(head);
printf("\nOnly node of the list deleted\n");
}

else
{
ptr = head;
while(ptr->next != NULL)
{
ptr1 = ptr;
ptr = ptr ->next;
}
ptr1->next = NULL;
free(ptr);
printf("\nDeleted Node from the last\n");
}
}
void random_delete()
{
struct node *ptr,*temp;
int loc,i;
printf("\nEnter the value of the node after which you want to perform deletion: ");
scanf("%d",&loc);
ptr=head;
while(temp->next!=NULL)
{
if (temp->data==loc)
{
temp->next=ptr->next;
free(ptr);
printf("\nNode has been deleted\n");
break;
}
else
printf("\nCant Delete");
temp=temp->next;
}
}
void display()
{
struct node *ptr;
ptr = head;
if(ptr == NULL)
{
printf("\nNothing to print");
}
else
{

while (ptr!=NULL)
{

14
printf("\n%d",ptr->data);
ptr = ptr -> next;
}
}
}

3. OUTPUT

15
4. VERIFICATION

5. RESULT: Thus, singly linked list was created and operations were performed on it.

16
LAB EXERCISE 3.1
07.01.19

LINKED LIST IMPLEMENTATION OF STACKS

1. PSEUDOCODE & ALGORITHM:

Algorithm to insert an element in a linked stack:


Step 1: Allocate memory for the new
node and name it as NEW_NODE
Step 2: SET NEW_NODE DATA = VAL
Step 3: IF TOP = NULL
SET NEW_NODE-> NEXT = NULL
SET TOP = NEW_NODE
ELSE
SET NEW_NODE NEXT = TOP
SET TOP = NEWNODE
[END OF IF]
Step 4: END
Algorithm to delete an element from a linked stack
Step 1: IF TOP = NULL
PRINT UNDERFLOW
[END OF IF]
Step 2: SET PTR = TOP
Step 4: FREE PTR
Step 5: END
Step 3: SET TOP = TOP -> NEXT

2. PROGRAM CODE:

#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*top,*top1,*temp;
int topelement();
void push(int data);
void pop();
void empty();
void display();
void destroy();
void stack_count();
void create();
int count = 0;
int main()
{
int no, ch, e;
printf("\n 1 - Push");
printf("\n 2 - Pop");
printf("\n 3 - Top");
printf("\n 4 - Empty");
printf("\n 5 - Exit");
printf("\n 6 - Dipslay");
printf("\n 7 - Stack Count");
printf("\n 8 - Destroy stack");
create();
while (1)

17
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
case 3:
if (top == NULL)
printf("No elements in stack");
else
{
e = topelement();
printf("\n Top element : %d", e);
}
break;
case 4:
empty();
break;
case 5:
exit(0);
case 6:
display();
break;
case 7:
stack_count();
break;
case 8:
destroy();
break;
default :
printf(" Wrong choice, Please enter correct choice ");
break;
}
}
return 0;
}
/* Create empty stack */
void create()
{
top = NULL;
}
/* Count stack elements */
void stack_count()
{
printf("\n No. of elements in stack : %d", count);
}

/* Push data into stack */


void push(int data)
{
if (top == NULL)
{
top =(struct node *)malloc(1*sizeof(struct node));
top->ptr = NULL;
top->info = data;
}
else
{
temp =(struct node *)malloc(1*sizeof(struct node));
temp->ptr = top;
temp->info = data;
top = temp;

18
}
count++;
}
/* Display stack elements */
void display()
{
top1 = top;
if (top1 == NULL)
{
printf("Stack is empty");
return;
}
while (top1 != NULL)
{
printf("%d ", top1->info);
top1 = top1->ptr;
}
}
/* Pop Operation on stack */
void pop()
{
top1 = top;
if (top1 == NULL)
{
printf("\n Error : Trying to pop from empty stack");
return;
}
else
top1 = top1->ptr;
printf("\n Popped value : %d", top->info);
free(top);
top = top1;
count--;
}
/* Return top element */
int topelement()
{
return(top->info);
}
/* Check if stack is empty or not */
void empty()
{
if (top == NULL)
printf("\n Stack is empty");
else
printf("\n Stack is not empty with %d elements", count);
}
/* Destroy entire stack */
void destroy()
{
top1 = top;
while (top1 != NULL)
{
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;
printf("\n All stack elements destroyed");
count = 0;
}

19
3. OUTPUT

4. VERIFICATION

20
LAB EXERCISE 3.2
07.01.19

LINKED LIST IMPLEMENTATION OF QUEUES AND ADDITIONAL

1. PSEUDOCODE & ALGORITHM:

Algorithm to insert an element in a linked queue:

Algorithm to delete an element in a linked queue:

2. PROGRAM CODE:

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

struct Node
{
int data;
struct Node *next;
}*front = NULL,*rear = NULL;

void insert(int);
void delete();
void display();

21
int main()
{
int choice, value;
printf("\n:: Queue Implementation using Linked List ::\n");
while(1){
printf("\n****** MENU ******\n");
printf("1. Insert\n2. Delete\n3. Display\n4. Exit\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice){
case 1: printf("Enter the value to be inserted: ");
scanf("%d", &value);
insert(value);
break;
case 2: delete(); break;
case 3: display(); break;
case 4: exit(0);
default: printf("\nWrong selection!!! Please try again!!!\n");
}
}
}
void insert(int value)
{
struct Node *newNode;
newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value;
newNode -> next = NULL;
if(front == NULL)
front = rear = newNode;
else{
rear -> next = newNode;
rear = newNode;
}
printf("\nInsertion is Successful!!!\n");
}
void delete()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
front = front -> next;
printf("\nDeleted element: %d\n", temp->data);
free(temp);
}
}
void display()
{
if(front == NULL)
printf("\nQueue is Empty!!!\n");
else{
struct Node *temp = front;
while(temp->next != NULL){
printf("%d--->",temp->data);
temp = temp -> next;
}
printf("%d--->NULL\n",temp->data);
}
}

22
3. OUTPUT

23
4. VERIFICATION

5. RESULT: Thus, stacks and queues were implemented using linked list.

24
LAB EXERCISE 4
21.01.19

IMPLEMENTATION OF BINARY SEARCH TREES

1. PSEUDOCODE & ALGORITHM:

Algorithm for in order traversal:


Step 1: Repeat Steps 2 to 4 while TREE != NULL
Step 2: INORDER(TREE-> LEFT)
Step 3: Write TREE-> DATA
Step 4: INORDER(TREE-> RIGHT)
[END OF LOOP]
Step 5: END
Algorithm for adding element to tree:
Inside recursion,
If (value > tree->data)
temp=tree->right
else
temp=tree->left
if(tree==null)
tree->data=value
Algorithm for deletion:

Node to be deleted is leaf: Simply remove from the tree.


Node to be deleted has only one child: Copy the child to the node and delete the child
Node to be deleted has two children: Find inorder successor of the node. Copy contents of the inorder successor to the node and
delete the inorder successor. Note that inorder predecessor can also be used.

2. PROGRAM CODE:

# include <stdio.h>
# include <conio.h>
# include <stdlib.h>
typedef struct BST {
int data;
struct BST *lchild, *rchild;
} node;
void insert(node *, node *);
void inorder(node *);
void preorder(node *);
void postorder(node *);
node *search(node *, int, node **);
int main() {
int choice;
char ans = 'N';
int key;
node *new_node, *root, *tmp, *parent;
node *get_node();
root = NULL;
printf("\nProgram For Binary Search Tree ");
do {
printf("\n1.Create");
printf("\n2.Search");
printf("\n3.Recursive Traversals");
printf("\n4.Exit");
printf("\nEnter your choice :");
scanf("%d", &choice);
switch (choice) {
case 1:

25
do {
new_node = get_node();
printf("\nEnter The Element ");
scanf("%d", &new_node->data);
if (root == NULL) /* Tree is not Created */
root = new_node;
else
insert(root, new_node);
printf("\nWant To enter More Elements?(y/n)");
ans = getch();
} while (ans == 'y');
break;
case 2:
printf("\nEnter Element to be searched :");
scanf("%d", &key);
tmp = search(root, key, &parent);
printf("\nParent of node %d is %d", tmp->data, parent->data);
break;
case 3:
if (root == NULL)
printf("Tree Is Not Created");
else {
printf("\nThe Inorder display : ");
inorder(root);
printf("\nThe Preorder display : ");
preorder(root);
printf("\nThe Postorder display : ");
postorder(root);
}
break;
}
} while (choice != 4);
}
/*
Get new Node
*/
node *get_node() {
node *temp;
temp = (node *) malloc(sizeof(node));
temp->lchild = NULL;
temp->rchild = NULL;
return temp;
}
/*
This function is for creating a binary search tree
*/
void insert(node *root, node *new_node) {
if (new_node->data < root->data) {
if (root->lchild == NULL)
root->lchild = new_node;
else
insert(root->lchild, new_node);
}

if (new_node->data > root->data) {


if (root->rchild == NULL)
root->rchild = new_node;
else
insert(root->rchild, new_node);
}
}
/*
This function is for searching the node from
binary Search Tree
*/
node *search(node *root, int key, node **parent) {
node *temp;
temp = root;
while (temp != NULL) {

26
if (temp->data == key) {
printf("\nThe %d Element is Present", temp->data);
return temp;
}
else
{
printf("\nThe %d Element is not Present", temp->data);
}
*parent = temp;
if (temp->data > key)
temp = temp->lchild;
else
temp = temp->rchild;
}
return NULL;
}
/*
This function displays the tree in inorder fashion
*/
void inorder(node *temp) {
if (temp != NULL) {
inorder(temp->lchild);
printf("%d ", temp->data);
inorder(temp->rchild);
}
}
/*
This function displays the tree in preorder fashion
*/
void preorder(node *temp) {
if (temp != NULL) {
printf("%d ", temp->data);
preorder(temp->lchild);
preorder(temp->rchild);
}
}
/*
This function displays the tree in postorder fashion
*/
void postorder(node *temp) {
if (temp != NULL) {
postorder(temp->lchild);
postorder(temp->rchild);
printf("%d ", temp->data);
}
}

27
3. OUTPUT

28
4. VERIFICATION

RESULT: Thus, a binary search tree was implemented and its uses were explored.

29
LAB EXERCISE 5.1
04.02.19

IMPLEMENTATION OF SEPARATE CHAINING

1. PSEUDOCODE & ALGORITHM:


STEP 1. Declare an array of a linked list with the hash table size.
STEP 2. Initialize an array of a linked list to NULL.
STEP 3. Find hash key.
STEP 4. If chain[key] == NULL
Make chain[key] points to the key node.
STEP 5. Otherwise(collision),
Insert the key node at the end of the chain[key].

2. PROGRAM CODE:
#include<stdio.h>
struct node
{ int ele;
struct node *next;
};
int arr[20];
struct node *head[10];
int hash(int x)
{ return x%10;
}
struct node* getnode(int ele)
{
struct node *newnode=(struct node*)malloc(sizeof(struct node));
newnode->ele=ele;
newnode->next=NULL;
return newnode;
}
void insert_list(struct node **head,int ele)
{ struct node *newnode=(struct node*)getnode(ele);
struct node *temp=*head;
if(temp==NULL)
*head=newnode;
else
{ while(temp->next!=NULL)
temp=temp->next;
temp->next=newnode;
}
printf("Element Added: %d\n",ele);
}
void insert_hash(int ele)
{ int index=hash(ele);
insert_list(&head[index],ele);
}
void print_list(struct node *head)
{ if(head==NULL)
{ printf("----");
printf("\n");
return;
}
while(head!=NULL)
{ printf("%d",head->ele);
if(head->next!=NULL)
printf("->");
head=head->next;
}

30
printf("\n");
}
void print_hash()
{ int i;
for(i=0;i<10;i++)
print_list(head[i]);
}
int main()
{ int ch,choice,ele;
do
{ printf("1. Enter an element\n");
printf("2. Show hash table\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{ case 1: printf("Enter element to be added: ");
scanf("%d",&ele);
insert_hash(ele);
break;
case 2: print_hash();
break;
default: printf("Wrong choice\n");

};
if(choice!=5)
{ printf("Do you want to enter again(1 for yes)? ");
scanf("%d",&ch);
}
else
ch=0;
}while(ch==1);

return 0;
}

3. OUTPUT

31
4. VERIFICATION

32
LAB EXERCISE 5.2
04.02.19

IMPLEMENTATION OF LINEAR PROBING

1. PSEUDOCODE & ALGORITHM:


STEP 1. Create an array of structure (i.e a hash table).
STEP 2. Take a key and a value to be stored in hash table as input.
STEP 3. Corresponding to the key, an index will be generated i.e every key is stored in a particular array index.
STEP 4. Using the generated index, access the data located in that array index.
STEP 5. In case of absence of data, create one and insert the data item (key and value) into it and increment the size of hash table.
STEP 6. In case the data exists, probe through the subsequent elements (looping back if necessary) for free space to insert new data
item.
Note: This probing will continue until we reach the same element again (from where we began probing)
STEP 7. To display all the elements of hash table, element at each index is accessed (via for loop).
STEP 8. To remove a key from hash table, we will first calculate its index and delete it if key matches, else probe through elements
until we find key or an empty space where not a single data has been entered (means data does not exist in the hash table).
STEP 9. Exit

2. PROGRAM CODE:
#include<stdio.h>
int array[10];
int hash(int x)
{ return x%10;
}
void insert(ele)
{ int index=hash(ele);
while(array[index]!=-1)
{ index++;
index=hash(index);
}
array[index]=ele;
}
void show()
{ int i;
for(i=0;i<10;i++)
{ if(array[i]==-1)
printf("....\n");
else
printf("%d\n",array[i]);
}
}
int main()
{ int ch,choice,ele;
int i;
for(i=0;i<10;i++)
array[i]=-1;
do
{ printf("1. Enter an element\n");
printf("2. Show hash table\n");
printf("Enter your choice: ");
scanf("%d",&choice);
switch(choice)
{ case 1: printf("Enter element to be added: ");
scanf("%d",&ele);
insert(ele);
break;
case 2: show();
break;
default: printf("Wrong choice\n");

33
};

printf("Do you want to enter again(1 for yes)? ");


scanf("%d",&ch);

}while(ch==1);
}

3. OUTPUT

34
4. VERIFICATION

35
LAB EXERCISE 5.3
04.02.19

IMPLEMENTATION OF DOUBLE HASHING (ADDITIONAL)

1. PSEUDOCODE & ALGORITHM:


STEP 1. Set indx = H(K); offset = H 2 (K)
STEP 2. If table location indx already contains the key, no need to insert it. Done!
STEP 3. Else if table location indx is empty, insert key there. Done!
STEP 4. Else collision. Set indx = (indx + offset) mod M.
STEP 5. If indx == H(K), table is full! (Throw an exception or enlarge table.) Else go to 2.
2. PROGRAM CODE:
#include<stdio.h>
#include<conio.h>
#include<math.h>
#include<stdlib.h>
struct data
{
int key;
int value;
};
struct hashtable_item
{
int flag;
/*
* flag = 0 : data not present
* flag = 1 : some data already present
* flag = 2 : data was present,but deleted
*/
struct data *item;

};
struct hashtable_item *array;
int max = 7;
int size = 0;
int prime = 3;
int hashcode1(int key)
{
return (key % max);
}
int hashcode2(int key)
{
return (prime - (key % prime));
}
void insert(int key, int value)
{
int hash1 = hashcode1(key);
int hash2 = hashcode2(key);
int index = hash1;
/* create new data to insert */
struct data *new_item = (struct data*) malloc(sizeof(struct data));
new_item->key = key;
new_item->value = value;
if (size == max)
{
printf("\n Hash Table is full, cannot insert more items \n");
return;
}
/* probing through other array elements */
while (array[index].flag == 1) {

36
if (array[index].item->key == key)
{
printf("\n Key already present, hence updating its value \n");
array[index].item->value = value;
return;
}
index = (index + hash2) % max;
if (index == hash1)
{
printf("\n Add is failed \n");
return;
}
printf("\n probing \n");
}
array[index].item = new_item;
array[index].flag = 1;
size++;
printf("\n Key (%d) has been inserted \n", key);
}
/* to remove an element from the array */
void remove_element(int key)
{
int hash1 = hashcode1(key);
int hash2 = hashcode2(key);
int index = hash1;
if (size == 0)
{
printf("\n Hash Table is empty \n");
return;
}
/* probing through other elements */
while (array[index].flag != 0)
{
if (array[index].flag == 1 && array[index].item->key == key)
{
array[index].item = NULL;
array[index].flag = 2;
size--;
printf("\n Key (%d) has been removed \n", key);
return;
}
index = (index + hash2) % max;
if (index == hash1)
{
break;
}
}
printf("\n Key (%d) does not exist \n", key);
}
int size_of_hashtable()
{
return size;
}
/* displays all elements of array */
void display()
{
int i;
for (i = 0; i < max; i++)
{
if (array[i].flag != 1)
{
printf("\n Array[%d] has no elements \n", i);
}
else
{
printf("\n Array[%d] has elements \n Key (%d) and Value (%d) \n", i, array[i].item->key,
array[i].item->value);
}
}

37
}
/* returns largest prime number less than size of array */
int get_prime()
{
int i,j;
for (i = max - 1; i >= 1; i--)
{
int flag = 0;
for (j = 2; j <= (int)sqrt(i); j++)
{
if (i % j == 0)
{
flag++;
}
}
if (flag == 0)
{
return i;
}
}
return 3;
}
/* initializes array */
void init_array()
{
int i;
for(i = 0; i < max; i++)
{
array[i].item = NULL;
array[i].flag = 0;
}
prime = get_prime();
}
int main()
{
int choice, key, value, n, c;
array = (struct hashtable_item*) malloc(max * sizeof(struct hashtable_item));
init_array();
do {
printf("Implementation of Hash Table in C with Double Hashing.\n\n");
printf("MENU-: \n1.Inserting item in the Hash Table"
"\n2.Removing item from the Hash Table"
"\n3.Check the size of Hash Table"
"\n4.Display Hash Table"
"\n\n Please enter your choice-:");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Inserting element in Hash Table\n");
printf("Enter key and value-:\t");
scanf("%d %d", &key, &value);
insert(key, value);
break;
case 2:
printf("Deleting in Hash Table \n Enter the key to delete-:");
scanf("%d", &key);
remove_element(key);
break;
case 3:
n = size_of_hashtable();
printf("Size of Hash Table is-:%d\n", n);
break;
case 4:
display();
break;
default:
printf("Wrong Input\n");
}

38
printf("\n Do you want to continue-:(press 1 for yes)\t");
scanf("%d", &c);

}while(c == 1);
}

3. OUTPUT

4. VERIFICATION

5. RESULT: Hence, different hashing techniques have been implemented.

39
LAB EXERCISE 6
09.02.19

IMPLEMENTATION OF MINIMUM HEAP AND ADDITIONAL

1. PSEUDOCODE & ALGORITHM:


Use array to store the data.
Start storing from index 1, not 0.
For any given node at position i:
Its Left Child is at [2*i] if available.
Its Right Child is at [2*i+1] if available.
Its Parent Node is at [i/2] if available.

2. PROGRAM CODE:
#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
int heap[1000000], heapSize;
void Init() {
heapSize = 0;
heap[0] = -INT_MAX;
}
void Insert(int element) {
heapSize++;
heap[heapSize] = element;int now = heapSize;
while (heap[now / 2] > element) {
heap[now] = heap[now / 2];
now /= 2;
}
heap[now] = element;
}
void printHeap(){

int i = 1;
printf("\n\t The output is:\n");
while(i<=heapSize){
printf("%d\n",heap[i]);
i = i + 1;
}
}
int main() {
int number_of_elements;
printf("Program to demonstrate Heap:\nEnter the number of elements: ");
scanf("%d", &number_of_elements);
int iter, element;
Init();
printf("Enter the elements: ");
for (iter = 0; iter < number_of_elements; iter++) {
scanf("%d", &element);
Insert(element);
}
printHeap();
return 0;
}

40
3. OUTPUT

4. VERIFICATION

5. ADDITIONAL: Add to minheap/maxheap if number is prime.


Maxheap algorithm:
Step 1 − Create a new node at the end of heap.
Step 2 − Assign new value to the node.
Step 3 − Compare the value of this child node with its parent.
Step 4 − If value of parent is less than child, then swap them.
Step 5 − Repeat step 3 & 4 until Heap property holds.

#include<stdio.h>
#include<stdlib.h>
#include<limits.h>
struct hash *ht=NULL;
int elecount=0,flagcount=0;
int heap[1000000], heapSize,heap2[100000];
void Init()
{
heapSize = 0;
heap[0]=INT_MAX;
}
struct node
{
int key;
};

struct hash
{
struct node *head;

41
};
struct node * createNode(int key)
{
struct node *newnode;
newnode = (struct node *)malloc(sizeof(struct node));
newnode->key = key;

return newnode;
}
int primecheck(int key)
{
int i,flag=0;
for(i=2;i<key;i++)
{
if(key%i==0)
{
flag=1;
break;
}
}
if(flag==0)
return 0;
if(flag==1)
return 1;
}
void maxinsert(int element)
{
heapSize++;
heap[heapSize] = element;
int now = heapSize;
while (heap[now / 2] < element)
{
heap[now] = heap[now / 2];
now /= 2;
}
heap[now] = element;
flagcount+=1;

void maxdisplay(int s)
{
int m,j;
for(j=0;j<heapSize;j++)
heap2[j]=heap[j];
int minElement, lastElement, child, now;
for(m=0;m<s;m++)
{
minElement = heap[1];
lastElement = heap[heapSize--];
for (now = 1; now * 2 <= heapSize; now = child) {
child = now * 2;
if (child != heapSize && heap[child + 1] > heap[child]) {
child++;
}
if (lastElement < heap[child]) {
heap[now] = heap[child];
} else
{
break;
}
}
heap[now] = lastElement;
printf("%d ",minElement);
}
for(j=0;j<s;j++){
heapSize+=1;
heap[j]=heap2[j];
}

42
}
void hashdisplay()
{
struct node *myNode;
int i;
for (i = 0; i < elecount; i++)
{
myNode = ht[i].head;
printf("\nData at index %d\t", i);
if(myNode==NULL)
printf("NULL");
else
{
printf("%d", myNode->key);

}
}
return;
}
void insert(int key)
{
int hashindex=key%elecount;
int i,check,flag=2;
if(ht[hashindex].head==NULL)
{
struct node *newnode=createNode(key);
ht[hashindex].head=newnode;
}
else
{
check=primecheck(key);
if(check==0)
maxinsert(key);
else
{
hashindex+=1;
for(i=hashindex;i<elecount;i++)
{
flag=0;
if(ht[hashindex].head!=NULL)
continue;
else
{
struct node *newnode=createNode(key);
ht[hashindex].head=newnode;
flag=1;
break;
}
}
}
}
if(flag==0)
printf("\nValue could not be added");
}

int main()
{
int ch,n=10,key;
elecount=n;
Init();
int s;
ht=(struct hash *)calloc(n, sizeof (struct hash));
printf("\n\n1. Insertion\n2. Display\n3. Exit");
do
{
printf("\nEnter choice: ");
scanf("%d",&ch);
switch(ch)
{

43
case 1: printf("Enter the key value:");
scanf("%d", &key);
getchar();
insert(key);
break;
case 2: s=flagcount;
hashdisplay();
printf("\nPrinting max heap:\n");
maxdisplay(s);
break;
case 3: printf("\n Exiting");
break;
default: printf("\nWrong option");break;
}
}while(ch!=3);

}
void mininsert(int key)
{
int hashindex=key%elecount;
int i,check,flag=2;
if(ht[hashindex].head==NULL)
{
struct node *newnode=createNode(key);
ht[hashindex].head=newnode;
}
else
{
check=primecheck(key);
if(check==0)
mininsert(key);
else
{
hashindex+=1;
for(i=hashindex;i<elecount;i++)
{
flag=0;
if(ht[hashindex].head!=NULL)
continue;
else
{
struct node *newnode=createNode(key);
ht[hashindex].head=newnode;
flag=1;
break;
}
}
}
}
if(flag==0)
printf("\nValue could not be added");
}

44
6. RESULT: Hence, max heap and min heap are implemented.

45
LAB EXERCISE 7.1
11.02.19

BUBBLE SORT

1. PSEUDOCODE & ALGORITHM:


begin BubbleSort(list)

for all elements of list


if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for

return list

end BubbleSort

2. PROGRAM CODE:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define max 100000
double time_spent = 0.0;
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void bubblesort(int a[], int n)
{
int i,j;
clock_t begin = clock();
for(i=0;i<n-1;i++)
for(j=0;j<n-i-1;j++)
if(a[j]>a[j+1])
swap(&a[j], &a[j+1]) ;
clock_t end = clock() ;
time_spent = ((double)(end - begin));
printf("The time spent is %lf.", time_spent);
for(i=600;i<620;i++)
{
printf("\n%d. %d", i+1, a[i]) ;
}
}
int main()
{
int a[max], i;
for(i=0;i<max;i++)
{
a[i] = rand()%100 + 1;
}
bubblesort(a,max/2) ;
return 0;
}

46
3. VERIFICATION

47
LAB EXERCISE 7.2
11.02.19

QUICK SORT

1. PSEUDOCODE & ALGORITHM:


Step 1 − Choose the highest index value has pivot
Step 2 − Take two variables to point left and right of the list excluding pivot
Step 3 − left points to the low index
Step 4 − right points to the high
Step 5 − while value at left is less than pivot move right
Step 6 − while value at right is greater than pivot move left
Step 7 − if both step 5 and step 6 does not match swap left and right
Step 8 − if left ≥ right, the point where they met is new pivot

2. PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

#define max 100000


double time_spent = 0.0;
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
int partition (int a[], int low, int high)
{
int pivot = a[high]; // pivot
int i = (low - 1); // Index of smaller element

for (int j = low; j <= high- 1; j++)


{
// If current element is smaller than or
// equal to pivot
if (a[j] <= pivot)
{
i++; // increment index of smaller element
swap(&a[i], &a[j]);
}
}
swap(&a[i + 1], &a[high]);
return (i + 1);
}

void quickSort(int a[], int low, int high)


{
if (low < high)
{
int pi = partition(a, low, high);

quickSort(a, low, pi - 1);


quickSort(a, pi + 1, high);
}

int main()

48
{
int a[max], i;
for(i=0;i<max;i++)
{
a[i] = rand()%100 + 1;
}
int n = max;
clock_t begin = clock();
quickSort(a, 0, n-1);
clock_t end = clock() ;
time_spent = ((double)(end - begin))/CLOCKS_PER_SEC;
printf("The time spent is %lf.", time_spent);

return 0;
}

3. VERIFICATION

49
LAB EXERCISE 7.3
11.02.19

MERGE SORT

1. PSEUDOCODE & ALGORITHM:


Step 1 − if it is only one element in the list it is already sorted, return.
Step 2 − divide the list recursively into two halves until it can no more be divided.
Step 3 − merge the smaller lists into new list in sorted order.

2. PROGRAM CODE:
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define max 100000
double time_spent = 0.0;
void swap(int *x, int *y)
{
int temp = *x;
*x = *y;
*y = temp;
}
void merge(int a[], int l, int m, int r)
{
int i, j, k;
int n1 = m - l + 1;
int n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = a[l + i];
for (j = 0; j < n2; j++)
R[j] = a[m + 1+ j];
i = 0; // Initial index of first subarray
j = 0; // Initial index of second subarray
k = l; // Initial index of merged subarray
while (i < n1 && j < n2)
{
if (L[i] <= R[j])
{
a[k] = L[i];
i++;
}
else
{
a[k] = R[j];
j++;
}
k++;
}
while (i < n1)
{
a[k] = L[i];
i++;
k++;
}
while (j < n2)
{
a[k] = R[j];
j++;

50
k++;
}
}

void mergesort(int a[], int l, int r)


{
if (l < r)
{
int m = l+(r-l)/2;
mergesort(a, l, m);
mergesort(a, m+1, r);
merge(a, l, m, r);
}
}
int main()
{
int a[max], i;
for(i=0;i<max;i++)
{
a[i] = rand()%100 + 1;
}
clock_t begin = clock();
mergesort(a,0,(max/10)-1) ;
for(i=690;i<700;i++)
{
printf("%d. %d\n", i+1, a[i]);
}
clock_t end = clock() ;
time_spent = ((double)(end - begin))/CLOCKS_PER_SEC;
printf("The time spent is %lf.", time_spent);
return 0;
}
3. COMBINED OUTPUT

51
4. VERIFICATION

5. RESULT: Thus, sorting algorithms were analysed.

52
LAB EXERCISE 8
18.02.19

IMPLEMENTATION OF LONGEST COMMON SUBSEQUENCE

1. PSEUDOCODE & ALGORITHM:


Algorithm: LCS-Length-Table-Formulation (X, Y)
m := length(X)
n := length(Y)
for i = 1 to m do
C[i, 0] := 0
for j = 1 to n do
C[0, j] := 0
for i = 1 to m do
for j = 1 to n do
if xi = yj
C[i, j] := C[i - 1, j - 1] + 1
B[i, j] := ‘D’
else
if C[i -1, j] ≥ C[i, j -1]
C[i, j] := C[i - 1, j] + 1
B[i, j] := ‘U’
else
C[i, j] := C[i, j - 1]
B[i, j] := ‘L’
return C and B

Algorithm: Print-LCS (B, X, i, j)


if i = 0 and j = 0
return
if B[i, j] = ‘D’
Print-LCS(B, X, i-1, j-1)
Print(xi)
else if B[i, j] = ‘U’
Print-LCS(B, X, i-1, j)
else
Print-LCS(B, X, i, j-1)

2. PROGRAM CODE:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int max(int a, int b);
void findLCS(char *X, char *Y, int XLen, int YLen);
int max(int a, int b) {
return (a > b)? a : b;
}
void findLCS(char *X, char *Y, int XLen, int YLen) {
int L[XLen + 1][YLen + 1];
int r, c, i;
for(r = 0; r <= XLen; r++) {
for(c = 0; c <= YLen; c++) {
if(r == 0 || c == 0) {
L[r][c] = 0;
} else if(X[r - 1] == Y[c - 1]) {
L[r][c] = L[r - 1][c - 1] + 1;
} else {
L[r][c] = max(L[r - 1][c], L[r][c - 1]);
}
}

53
}
r = XLen;
c = YLen;
i = L[r][c];
char LCS[i+1];
LCS[i] = '\0';
while(r > 0 && c > 0) {
if(X[r - 1] == Y[c - 1]) {
LCS[i - 1] = X[r - 1];
i--;
r--;
c--;
} else if(L[r - 1][c] > L[r][c - 1]) {
r--;
} else {
c--;
}
}
printf("LCS: %s\n", LCS);
}

int main(void) {
printf("\nInput strings:\n ");
char X[1000];
char Y[1000];
printf("\n");
gets(X);
printf("\n");
gets(Y);
int XLen = strlen(X);
int YLen = strlen(Y);
findLCS(X, Y, XLen, YLen);
return 0;
}

3. OUTPUT

4. VERIFICATION

5. RESULT: Thus, the longest common subsequence was identified.

54
LAB EXERCISE 9
25.02.19

IMPLEMENTATION OF MINIMUM SPANNING TREE WITH PRIM’S AND KRUSKAL’S


ALGORITHM

1. PSEUDOCODE & ALGORITHM:


A. PRIM’S
Step 1 - Remove all loops and parallel edges
Step 2 - Choose any arbitrary node as root node
Step 3 - Check outgoing edges and select the one with less cost

B. KRUSKAL’S
Step 1 - Remove all loops and Parallel Edges
Step 2 - Arrange all edges in their increasing order of weight
Step 3 - Add the edge which has the least weightage

2. PROGRAM CODE:
A. PRIM’S

#include<stdio.h>
#include<stdlib.h>
#include<conio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
int main()

{
printf("\nEnter the number of nodes:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\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;
}
visited[1]=1;
printf("\n");
while(ne < n)
{
for(i=1,min=999;i<=n;i++)
for(j=1;j<=n;j++)
if(cost[i][j]< min)
if(visited[i]!=0)
{
min=cost[i][j];
a=u=i;
b=v=j;
}
if(visited[u]==0 || visited[v]==0)
{
printf("\n Edge %d:(%d %d) cost:%d",ne++,a-1,b-1,min);
mincost+=min;

55
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
getch();
}
B. KRUSKAL’S
/// kruskal's program
#include<stdio.h>
#define MAX 30
typedef struct edge
{
int u,v,w;
}edge;
typedef struct edgelist
{
edge data[MAX];
int n;
}edgelist;
edgelist elist;
int G[MAX][MAX],n;
edgelist spanlist;
void kruskal();
int find(int belongs[],int vertexno);
void union1(int belongs[],int c1,int c2);
void sort();
void print();

void main()
{
int i,j,total_cost;
printf("\nEnter number of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
kruskal();
print();
}
void kruskal()
{
int belongs[MAX],i,j,cno1,cno2;
elist.n=0;

for(i=1;i<n;i++)
for(j=0;j<i;j++)
{
if(G[i][j]!=0)
{
elist.data[elist.n].u=i;
elist.data[elist.n].v=j;
elist.data[elist.n].w=G[i][j];
elist.n++;
}
}

sort();
for(i=0;i<n;i++)
belongs[i]=i;
spanlist.n=0;
for(i=0;i<elist.n;i++)
{
cno1=find(belongs,elist.data[i].u);
cno2=find(belongs,elist.data[i].v);
if(cno1!=cno2)
{
spanlist.data[spanlist.n]=elist.data[i];

56
spanlist.n=spanlist.n+1;
union1(belongs,cno1,cno2);
}
}
}
int find(int belongs[],int vertexno)
{
return(belongs[vertexno]);
}
void union1(int belongs[],int c1,int c2)
{
int i;

for(i=0;i<n;i++)
if(belongs[i]==c2)
belongs[i]=c1;
}
void sort()
{
int i,j;
edge temp;
for(i=1;i<elist.n;i++)
for(j=0;j<elist.n-1;j++)
if(elist.data[j].w>elist.data[j+1].w)
{
temp=elist.data[j];
elist.data[j]=elist.data[j+1];
elist.data[j+1]=temp;
}
}

void print()
{
int i,cost=0;
for(i=0;i<spanlist.n;i++)
{
printf("\n%d\t%d\t%d",spanlist.data[i].u,spanlist.data[i].v,spanlist.data[i].w);
cost=cost+spanlist.data[i].w;
}

printf("\n\nCost of the spanning tree=%d",cost);


}

57
3. OUTPUT

58
4. VERIFICATION

PRIM’S KRUSKAL’S

5. RESULT: Thus, Prim’s and Kruskal’s greedy algorithms were implemented.

59
LAB EXERCISE 10.1
11.03.19

IMPLEMENTATION OF BREADTH FIRST SEARCH

1. PSEUDOCODE & ALGORITHM:

STEP 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Insert it in a queue.
STEP 2 − If no adjacent vertex is found, remove the first vertex from the queue.
STEP 3 − Repeat STEP 1 and STEP 2 until the queue is empty.

2. PROGRAM CODE:
#include<stdio.h>
#include<stdlib.h>

#define MAX 100

#define initial 1
#define waiting 2
#define visited 3

int n;
int adj[MAX][MAX];
int state[MAX];
void create_graph();
void BF_Traversal();
void BFS(int v);

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


void insert_queue(int vertex);
int delete_queue();
int isEmpty_queue();

int main()
{
create_graph();
BF_Traversal();
return 0;
}

void BF_Traversal()
{
int v;
for(v=0; v<n; v++)
state[v] = initial;
printf("Enter Start Vertex for BFS: \n");
scanf("%d", &v);
BFS(v);
}

void BFS(int v)
{
int i;
insert_queue(v);
state[v] = waiting;
while(!isEmpty_queue())
{
v = delete_queue( );
printf("%d ",v);

60
state[v] = visited;
for(i=0; i<n; i++)
{
if(adj[v][i] == 1 && state[i] == initial)
{
insert_queue(i);
state[i] = waiting;
}
}
}
printf("\n");
}

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 isEmpty_queue()
{
if(front == -1 || front > rear)
return 1;
else
return 0;
}

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

void create_graph()
{
int count,max_edge,origin,destin;

printf("Enter number of vertices : ");


scanf("%d",&n);
max_edge = n*(n-1);

for(count=1; count<=max_edge; count++)


{
printf("Enter edge %d( -1 -1 to quit ) : ",count);
scanf("%d %d",&origin,&destin);

if((origin == -1) && (destin == -1))


break;

if(origin>=n || destin>=n || origin<0 || destin<0)


{
printf("Invalid edge!\n");
count--;
}
else

61
{
adj[origin][destin] = 1;
}
}
}

3. OUTPUT

4. VERIFICATION

62
LAB EXERCISE 10.2
11.03.19

IMPLEMENTATION OF DEPTH FIRST SEARCH

1. PSEUDOCODE & ALGORITHM:


STEP 1 − Visit the adjacent unvisited vertex. Mark it as visited. Display it. Push it in a stack.
STEP 2 − If no adjacent vertex is found, pop up a vertex from the stack. (It will pop up all the vertices from the stack, which do not
have adjacent vertices.)
STEP 3 − Repeat STEP 1 and STEP 2 until the stack is empty.

2. PROGRAM CODE:

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

struct node
{
int vertex;
struct node* next;
};

struct node* createNode(int v);

struct Graph
{
int numVertices;
int* visited;
struct node** adjLists; // we need int** to store a two dimensional array. Similary, we need struct node** to store an array of
Linked lists
};

struct Graph* createGraph(int);


void addEdge(struct Graph*, int, int);
void printGraph(struct Graph*);
void DFS(struct Graph*, int);

int main()
{

struct Graph* graph = createGraph(7);


addEdge(graph, 0, 1);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 4);
addEdge(graph, 3, 4);
addEdge(graph, 6, 3);
addEdge(graph, 4, 5);

printGraph(graph);

DFS(graph, 0);

return 0;
}

void DFS(struct Graph* graph, int vertex) {


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

63
graph->visited[vertex] = 1;
printf("Visited %d \n", vertex);

while(temp!=NULL) {
int connectedVertex = temp->vertex;

if(graph->visited[connectedVertex] == 0) {
DFS(graph, connectedVertex);
}
temp = temp->next;
}
}

struct node* createNode(int v)


{
struct node* newNode = malloc(sizeof(struct node));
newNode->vertex = v;
newNode->next = NULL;
return newNode;
}

struct Graph* createGraph(int vertices)


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

graph->adjLists = malloc(vertices * sizeof(struct node*));

graph->visited = malloc(vertices * sizeof(int));

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

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


{
// Add edge from src to dest
struct node* newNode = createNode(dest);
newNode->next = graph->adjLists[src];
graph->adjLists[src] = newNode;

// Add edge from dest to src


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

void printGraph(struct Graph* graph)


{
int v;
for (v = 0; v < graph->numVertices; v++)
{
struct node* temp = graph->adjLists[v];
printf("\n Adjacency list of vertex %d\n ", v);
while (temp)
{
printf("%d -> ", temp->vertex);
temp = temp->next;
}
printf("\n");
}
}

64
3. OUTPUT

4. VERIFICATION

5. RESULT: Thus, DFS and BFS were implemented.

65
LAB EXERCISE 11
18.03.19

IMPLEMENTATION OF SHORTEST PATH ALGORITHM

1. PSEUDOCODE & ALGORITHM:


STEP 1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in shortest path tree, i.e., whose minimum
distance from source is calculated and finalized. Initially, this set is empty.
STEP 2) Assign a distance value to all vertices in the input graph. Initialize all distance values as INFINITE. Assign distance value as 0
for the source vertex so that it is picked first.
STEP 3) While sptSet doesn’t include all vertices
a) Pick a vertex u which is not there in sptSet and has minimum distance value.
b) Include u to sptSet.
c) Update distance value of all adjacent vertices of u. To update the distance values, iterate through all adjacent vertices.
For every adjacent vertex v, if sum of distance value of u (from source) and weight of edge u-v, is less than the distance
value of v, then update the distance value of v.

2. PROGRAM CODE:

#include<stdio.h>
#include<conio.h>
#define INFINITY 9999
#define MAX 10

void dijkstra(int G[MAX][MAX],int n,int startnode);

int main()
{
int G[MAX][MAX],i,j,n,u;
printf("Enter no. of vertices:");
scanf("%d",&n);
printf("\nEnter the adjacency matrix:\n");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&G[i][j]);
printf("\nEnter the starting node:");
scanf("%d",&u);
dijkstra(G,n,u);
return 0;
}

void dijkstra(int G[MAX][MAX],int n,int startnode)


{

int cost[MAX][MAX],distance[MAX],pred[MAX];
int visited[MAX],count,mindistance,nextnode,i,j;
//pred[] stores the predecessor of each node
//count gives the number of nodes seen so far
//create the cost matrix
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];
//initialize pred[],distance[] and visited[]
for(i=0;i<n;i++)
{
distance[i]=cost[startnode][i];

66
pred[i]=startnode;
visited[i]=0;
}
distance[startnode]=0;
visited[startnode]=1;
count=1;
while(count<n-1)
{
mindistance=INFINITY;
//nextnode gives the node at minimum distance
for(i=0;i<n;i++)
if(distance[i]<mindistance&&!visited[i])
{
mindistance=distance[i];
nextnode=i;
}
//check if a better path exists through nextnode
visited[nextnode]=1;
for(i=0;i<n;i++)
if(!visited[i])
if(mindistance+cost[nextnode][i]<distance[i])
{
distance[i]=mindistance+cost[nextnode][i];
pred[i]=nextnode;
}
count++;
}

//print the path and distance of each node


for(i=0;i<n;i++)
if(i!=startnode)
{
printf("\nDistance of node%d=%d",i,distance[i]);
printf("\nPath=%d",i);
j=i;
do
{
j=pred[j];
printf("<-%d",j);
}while(j!=startnode);
}
}

67
3. OUTPUT

4. VERIFICATION

5. RESULT: Thus, Dijkstra’s algorithm was implemented.

68
69
70

You might also like