CS3311 Datastructures Laboratory
CS3311 Datastructures Laboratory
ARMCET
(Approved by AICTE & Affiliated to Anna University)
Registration Number :
Year of Study :
Semester :
ARM COLLEGE OF ENGINEERING AND TECHNOLOGY
SATTAMANGALAM, MARAIMALAI NAGAR, CHENNAI, TAMIL NADU. PIN-603 209.
ARMCET
(Approved by AICTE & Affiliated to Anna University)
BONAFIDE CERTIFICATE
Reg. No.
AIM
To implement queue operations using array.
ALGORITHM
1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
If choice = 1
thenIfrear
<max -1
Increment rear
Store element at current position of rear
Else
Print Queue Full
Else If choice = 2
then Iffront = –1 then
Print Queue empty
Else
Display current front
elementIncrement front
Else If choice = 3 then
Display queue elements starting from front to rear.
6.Stop
PROGRAM
#include <stdio.h>
#include <conio.h>
#define max 5
static int queue[max];
int front = -1;
int rear = -1;
void insert(int x)
{
queue[++rear] = x;
if (front == -1)
front = 0;
}
int remove()
{
int val;
val = queue[front];
if (front==rear && rear==max-1)
front = rear = -1;
else
front ++;
return (val);
}
void view()
{
int i;
if (front == -1)
printf("\n Queue Empty \n");
else
{
printf("\n Front-->");
for(i=front; i<=rear; i++)
printf("%4d", queue[i]);
printf(" <--Rear\n");
}
}
void main()
{
int ch= 0,val;
clrscr();
while(ch != 4)
{
printf("\n QUEUE OPERATION \n");
printf("1.INSERT");
printf("2.DELETE");
printf("3.VIEW");
printf("4.QUIT\n");
printf("Enter Choice :");
scanf("%d", &ch);
switch(ch)
{
case 1:
if(rear < max-1)
{
printf("\n Enter element to be inserted : ");
scanf("%d", &val);
insert(val);
}
else
printf("\n Queue Full \n");
break;
case 2:
if(front == -1)
QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1
QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1
QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1
QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1
QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1
QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 1
Queue Full
QUEUE OPERATION
1. INSERT 2.DELETE 3.VIEW 4.QUIT
Enter Choice: 3
Front--> 12 23 34 45 56 <--Rear
RESULT
Thus, the C program for the implementation of array queue in ADT is executed successfully.
Ex. No. 1b Array implementation of Stack ADT
Date:
AIM
To implement stack operations using array.
ALGORITHM
1. Start
2. Define a array stack of size max = 5
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
If top < max -1
Increment top
Store element at current position of top
Else
Print Stack overflow
Else If choice = 2 then
If top < 0 then
Print Stack underflow
Else
Display current top
elementDecrement top
Else If choice = 3 then
Display stack elements starting from top
7. Stop
PROGRAM
#include <stdio.h>
#include <conio.h>
#define max 5
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return (stack[top--]);
}
void view()
{
int i;
if (top < 0)
printf("\n Stack Empty \n");
else
{
printf("\n Top-->");
for(i=top; i>=0; i--)
{
printf("%4d", stack[i]);
}
printf("\n");
}
}
void main()
{
int ch=0, val;
clrscr();
while(ch != 4)
{
printf("\nSTACK OPERATION”);
printf("1.PUSH ");
printf(“2.POP”);
printf(“3.VIEW”);
printf("4.QUIT \n"); 0.
printf("Enter Choice :");
scanf("%d", &ch);
switch(ch)
{
case 1:
if(top < max-1)
{
printf("\nEnter Stack element : ");
scanf("%d",&val);
push(val);
}
else
OUTPUT
STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 1
STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 1
STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 1
STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 3
Top - > 45 34 23 12
STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 2
Popped element is 45
STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 3
Top--> 34 23 12
STACK OPERATION
1. PUSH 2.POP 3.VIEW 4.QUIT
Enter Choice: 4
RESULT
Thus the C program for the implementation of Stack using arrays is executed successfully.
Ex. No. 1c Array implementation of Circular Queue ADT
Date:
AIM
To implement Circular Queue operations using array.
ALGORITHM
Step 1: IF FRONT = -1
Write “UNDERFLOW”
Goto Step 4
[END of IF]
Step 2: SET VAL = QUEUE [FRONT]
Step 3: IF FRONT = REAR
SET FRONT = REAR = -1
ELSE
IF FRONT = MAX -1
SET FRONT = 0
ELSE
SET FRONT = FRONT + 1
[END of IF]
[END OF IF]
Step 4: EXIT
PROGRAM
#include <stdio.h>
# define max 6
int queue[max]; // array declaration
int front=-1;
int rear=-1;
// function to insert an element in a circular queue
Void enqueue(int element)
{
if(front==-1 && rear==-1) // condition to check queue is empty
{
front=0;
rear=0;
queue[rear]=element;
}
else if((rear+1)%max==front) // condition to check queue is full
{
printf("Queue is overflow..");
}
else
{
rear=(rear+1)%max; // rear is incremented
queue[rear]=element; // assigning a value to the queue at the rear positin.
}}
// function to delete the element from the queue
int dequeue()
{
if ((front==-1) && (rear==-1)) // condition to check queue is empty
{
printf("\nQueue is underflow..");
}
else if(front==rear)
{
printf("\nThe dequeued element is %d", queue[front]); front=-
1;
rear=-1;
}
else {
printf("\nThe dequeued element is %d", queue[front]);
front=(front+1)%max;
}}
// function to display the elements of a queue
void display()
{
int i=front;
if(front==-1 && rear==-1)
{
printf("\n Queue is empty..");
}
else
{
printf("\nElements in a Queue are :");
while(i<=rear)
{
printf("%d,", queue[i]);
i=(i+1)%max;
} }}
int main()
{
int choice=1,x; // variables declaration
while(choice<4 && choice!=0) // while loop
{
printf("\n Press 1: Insert an element");
printf("\nPress 2: Delete an element");
printf("\nPress 3: Display the element");
printf("\nEnter your choice"); scanf("%d",
&choice);
switch(choice)
{
case 1:
printf("Enter the element which is to be inserted");
scanf("%d", &x);
enqueue(x);
break;
case 2:
dequeue();
break;
case 3:
display(); }}
return 0;
}
OUTPUT
RESULT:
Thus the C program for the implementation of Circular Queue ADT is executed successfully.
Ex.No:2 IMPLEMENTATION OF SINGLY LINKED LIST
Date:
AIM:
ALGORITHM:
Step1: Create nodes first, last; next, prev and cur then set the value as NULL.
Step 2: Read the list operation type.
Step 3: If operation type is create then process the following steps.
1. Allocate memory for node cur.
2. Read data in cur's data area.
3. Assign cur node as NULL.
4. Assign first=last=cur.
1. Allocate memory for node cur.
2. Read data in cur's data area.
3. Read the position the Data to be insert.
4. Availability of the position is true then assign cur's node as first and first=cur.
5. If availability of position is false then do following steps.
1.Assign next as cur and count as zero.
2. Repeat the following steps until count less than position.
1 .Assign prev as next
2. Next as prev of node.
3. Add count by one.
4. If prev as NULL then display the message INVALID POSITION.
5. If prev not equal to NULL then do the following steps.
1. Assign cur's node as prev's node.
2. Assign prev's node as cur.
1. Read the position .
2. Check list is Empty .If it is true display the message List empty.
3. If position is first.
1. Assign cur as first.
2. Assign First as first of node.
3. Reallocate the cur from memory.
4. If position is last.
1. Move the current node to prev.
2. cur's node as Null.
3. Reallocate the Last from memory.
4. Assign last as cur.
5. If position is enter Mediate.
1. Move the cur to required postion.
2. Move the Previous to cur's previous position
3. Move the Next to cur's Next position.
4. Now Assign previous of node as next.
5. Reallocate the cur from memory.
Step 4: If operation is traverse.
1. Assign current as first.
2. Repeat the following steps untill cur becomes NULL.
PROGRAM:
#include<stdio.h>
#include<conio.h>
#define null 0
typedef struct n
{
int data;
struct n*next;
}
node;
node*head=null,*newn,*temp,*t;
void insert();
void delete();
void view();
void main()
{
int choice;
clrscr();
printf("\n\t\t SINGLY LINKED LIST");
while (1)
{
printf("\n 1.Insert\t 2.Delete\t 3.View");
printf("\n Enter the choice:");
scanf("%d", &choice);
switch(choice)
{
case 1:insert();
break;
case 2:delete();
break;
case 3:view();
break;
case 4:exit(0);
break;
default: printf("\n Enter the correct option");
}
}
}
void insert()
{
int option,no;
newn=(node*)malloc(sizeof(node));
printf("Enter the data to be inserted : ");
scanf("%d",&newn->data);
newn->next=null;
printf("\n 1.Insert first\t 2.Insert middle\t 3.Insert last");
printf("\n Enter the option:");
scanf("%d", &option);
switch (option)
{
case 1:if(head==null)
head=newn;
else
{
newn-> next=head;
head=newn;
}
break;
case 2:if(head-> next==null)
printf("single entry list cannot perform insertion in the middle");
else
{
printf("\n entry the data which the node has to insert");
scanf("%d",&no);
temp=head;
while(temp->data!=no)
{
temp=temp-> next;
}
newn->next=temp->next;
temp->next = newn;
}
break;
case 3:temp=head;
if(head == null)
head=newn;
else
{
temp=head;
while(temp->next!=null)
{
temp=temp->next;
}
temp->next = newn;
}
break;
}
}
void delete()
{
int option,no;
if(head==null)
{
printf("empty list cannot perform deletion");
}
printf("1.Deletion at first\t 2.Deletion in middle\t 3.Deletion at last\n");
printf(“Enter the Option : “);
scanf("%d",&option);
switch (option)
{
case 1: temp=head;
head =head->next;
printf("The data deleted is %d",temp ->data);
free(temp);
break;
case 2:if(head->next == null)
printf("single entry list cannot perform deletion at middle");
else
{
printf("Enter the data which has to be deleted : ");
scanf("%d",&no);
temp=head;
while(temp->data!=no)
{
t=temp;
temp=temp->next;
}
printf("the data deleted is %d",temp->data);
t->next=temp->next;
free(temp);
}
break;
case 3:temp=head;
if(head->next == null)
{
printf("the data deleted is%d",head->data);
head=null;
}
else
{
while(temp->next!=null)
{
t=temp;
temp=temp->next;
printf("the data deleted is%d",temp->data);
free (temp);
}
}
break;
}
}
void view()
{
temp=head;
printf("Head-->");
while(temp!=null)
{
printf("%d->\t",temp->data);
temp=temp->next;
}
printf("NULL");
}
OUTPUT:
SINGLY LINKED LIST
1.Insert 2.Delete 3.View
Enter the choice: 1
Enter the data to be inserted : 11
1.Insert first 2.Insert middle 3.Insert last
Enter the option : 1
1.Insert 2.Delete 3.View
RESULT:
Thus, the C program for Linked list implementation of List ADT was created, executed and
output was verified successfully.
Ex. No. 3a Linked list implementation of Stack ADT
Date:
AIM
To implement stack operations using linked list.
ALGORITHM
1. Start
2. Define a singly linked list node for stack
3. Create Head node
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
Create a new node with data
Make new node point to first node
Make head node point to new node
Else If choice = 2 then
Make temp node point to first node
Make head node point to next of temp node
Release memory
Else If choice = 3 then
Display stack elements starting from head node till null
7. Stop
PROGRAM
#include <stdio.h>
#include <conio.h>
#include <process.h>
#include <alloc.h>
struct node
{
int label;
struct node *next;
};
main()
{
int ch = 0;
int k;
struct node *h, *temp, *head;
switch(ch)
{
case 1:
/* Create a new node */
temp=(struct node *)(malloc(sizeof(struct node)));
printf("Enter label for new node : ");
scanf("%d", &temp->label);
h = head;
temp->next = h->next;
h->next = temp;
break;
case 2:
/* Delink the first node */
h = head->next;
head->next = h->next;
printf("Node %s deleted\n", h->label);
free(h);
break;
case 3:
printf("\n HEAD -> ");
h = head;
/* Loop till last node */
while(h->next != NULL)
{
h = h->next;
printf("%d -> ",h->label);
}
printf("NULL \n");
break;
case 4:
exit(0);
}
}
}
OUTPUT
RESULT:
Thus push and pop operations of a stack was demonstrated using linked list.
Ex.No:3b
Date:
IMPLEMENTATION OF LINEAR QUEUE ADT USING LINKED LIST
AIM:
ALGORITHM:
1. Define a struct for each node in the queue. Each node in the queue contains data and
link to the next node. Front and rear pointer points to first and last node inserted in the queue.
2.The operations on the queue are
a. INSERT data into the queue
b.DELETE data out of queue
3.PUSH DATA INTO STACK
a.Enter the data to be inserted into stack.
b.If TOP is NULL
i.The input data is the first node in stack.
ii.The link of the node is NULL.
iii.TOP points to that node.
c.If TOP is NOT NULL
i.The link of TOP points to the new node.
ii.TOP points to that node.
4.POP DATA FROM STACK
a.If TOP is NULL
i. the stack is empty
b.If TOP is NOT NULL
i.The link of TOP is the current TOP.
ii.The pervious TOP is popped from stack.
OUTPUT:
Program For Queue Using Linked List
Main Menu
1.Insert
2.Delete
3.Display
Enter Your Choice1
Insert the element in the Queue 65
Do you want to continue?
Program For Queue Using Linked List
Main Menu
1.Insert
2.Delete
3.Display
Enter Your Choice 1
Insert the element in the Queue 71
Do you want to continue?
Program For Queue Using Linked List
Main Menu
1.Insert
2.Delete
3.Display
65 71 51
Do you want to continue?
Program For Queue Using Linked List
Main Menu
1. Insert
2.Delete
3.Display
Enter Your Choice2
The deleted Element Is 65
RESULT:
Thus, the C program for linked list implementation of Queue ADT was created, executed and output
was verified successfully.
Ex.No:4 IMPLEMENTATION OF POLYNOMIAL MANIPULATION USING
Date: LINKED LIST
AIM:
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<process.h>
#include<stdlib.h>
#define TRUE 1
#define FALSE 0
typedef struct pnode
{
float coef;
int exp;
struct pnode *next;
}p;
void main()
{
p *p1,*p2,*p3;
p *get_poly(),*add(p*,p*);
void display(p*);
printf("\n Enter the first polynomial\n\n");
p1=get_poly();
printf("\nEnter the second polynomial is \n");
p2=get_poly();
printf("\nThe first polynomial is\n");
display(p1);
printf("\nThe second polynomial is\n");
display(p2);
p3=add(p1,p2);
printf("\nThe addition of the polynomials is...\n");
display(p3);
exit(0);
}
p *get_poly()
{
p *temp,*new,*last;
int Exp,flag;
float coef;
p *get_node();
char ans='y';
temp=NULL;
flag=TRUE;
printf("\nEnter the polynomial in descending order of exponent\n");
do
{
printf("\nEnter the Coefficient and Exponent of a temp:");
scanf("%f%d",&coef,&Exp);
New=(p*)malloc(sizeof(p));
if(New==NULL)
printf("memory cannot be allocated");
New->coef=coef;
New->exp=Exp;
New->next=NULL;
if(flag==TRUE)
{
temp=New;
last=temp;
flag=FALSE;
}
else
{
last->next=new;
last=new;
}
printf("\n Do you Want To Add more terms?(y/n)");
ans=getch();
32
}
while(ans=='y');
return(temp);
}
void display(p *head)
{
p *temp;
temp=head;
if(temp==NULL)
{
printf("The polynomial is empty\n");
getch();
return; }
printf("\n");
while(temp->next!=NULL)
{
printf("%0.1fx^%d+",temp->coef,temp->exp);
temp=temp->next;
}
printf("%0.1fx^%d",temp->coef,temp->exp);
getch();
}
p *add(p*first,p*second)
{
p *p1,*p2,*temp,*dummy;
char ch;
float coef;
p *append(int,float,p*);
p1=first;
p2=second;
temp=(p*)malloc(sizeof(p));
if(temp==NULL)
printf("\nMomorycan not be allocated");
dummy=temp;
while(p1 != NULL&&p2!= NULL)
{
if(p1->exp==p2->exp)
{
coef=p1->coef+p2->coef;
temp=append(p1->exp,coef,temp);
p1=p1->next;
p2=p2->next; }
else if(p1->exp<p2->exp)
{
coef=p2->coef;
temp=append(p2->exp,coef,temp);
p2=p2->next;
}
else if(p1->exp<p2->exp)
{
coef=p2->coef;
temp=append(p2->exp,coef,temp);
p2=p2->next; }
else if(p1->exp>p2->exp)
{
coef=p1->coef;
temp=append(p1->exp,coef,temp);
p1=p1-> next; }}
while(p1!=NULL)
{
temp=append(p1->exp,p1->coef,temp);
p1=p1-> next; }
while(p2!=NULL)
{
temp=append(p2->exp,p2->coef,temp);
p2=p2-> next; }
temp->next=NULL;
temp=dummy->next;
free(dummy);
return(temp); }
p *append(int Exp,floatcoef,p*temp)
{
p *New,*dummy;
New=(p*)malloc(sizeof(p));
if(New==NULL)
printf("\n Memory cannot be allocated\n");
New->exp=Exp;
New->coef=coef;
New->next=NULL;
dummy=temp;
dummy->next=New;
dummy=New;
return(dummy);
}
OUTPUT:
Enter the first polynomial
Enter the polynomial in descending order of exponent
Enter the Coefficient and Exponent of a temp: 5 3
Do you Want To Add more terms?(y/n)
Enter the Coefficient and Exponent of a temp:3 3
Do you Want To Add more terms?(y/n)
Enter the Coefficient and Exponent of a temp:2 2
Do you Want To Add more terms?(y/n)
Enter the Coefficient and Exponent of a temp:1 1
Do you Want To Add more terms?(y/n)
Enter the second polynomial is
Enter the polynomial in descending order of exponent
Enter the Coefficient and Exponent of a temp:4 3
Do you Want To Add more terms?(y/n)
Enter the Coefficient and Exponent of a temp: 3 3Do
you Want To Add more terms?(y/n)
Enter the Coefficient and Exponent of a temp:5 2
Do you Want To Add more terms?(y/n)
The first polynomial is
5.0x^3+3.0x^3+2.0x^2+1.0x^1
The second polynomial is
4.0x^3+3.0x^3+5.0x^2
The addition of the polynomials is...
9.0x^3+6.0x^3+7.0x^2+1.0x^1
RESULT:
Thus, a polynomial equation was implemented and executed successfully.
Ex. No: 5 Evaluating Postfix Expressions- Infix to Postfix Conversion
Date:
AIM
ALGORITHM
1. Start
2. Define a array stack of size max = 20
3. Initialize top = -1
4. Read the infix expression character-by-character If
character is an operand print it
If character is an operator
Compare the operator’s priority with the stack[top] operator.
If the stack [top] has higher/equal priority than the input operator,
Pop it from the stack and print it.
Else
Push the input operator onto the stack
If character is a left parenthesis, then push it onto the stack.
If character is a right parenthesis, pop all operators from stack and print it until a
left parenthesis is encountered. Do not print the parenthesis. If character = $
then Pop out all operators, Print them and Stop
PROGRAM
#include <stdio.h>
#include <conio.h>
#include <string.h>
#define MAX 20
break;
default:
return 0;
}
}
j++;
}
postfix[j] = '\0';
}
main()
{
char infix[20],postfix[20];
clrscr();
printf("Enter the valid infix string: ");
gets(infix);
convertip(infix, postfix);
printf("The corresponding postfix string is: ");
puts(postfix);
getch();
}
void push(char item)
{
top++;
stack[top] = item;
}
char pop()
{
char a;
a = stack[top];
top--;
return a;
}
OUTPUT
Enter the valid infix string: (a+b*c)/(d$e)
The corresponding postfix string is: abc*+de$/
RESULT
Thus the given infix expression was converted into postfix form using stack.
Ex. No:6 Implementation of Binary Search Tree
Date:
AIM
To insert and delete nodes in a binary search tree.
ALGORITHM
1. Create a structure with key and 2 pointer variable left and right.
2. Read the node to be inserted.
If (root==NULL)
root=node
else if (root>key<node-
>key) root->right=NULL
else
Root->left=node
3. For Deletion
if it is a leaf node
Remove immediately
Remove pointer between del node &
child if it is having one child
Remove link between del node&child
Link delnode is child with delnodes
parent
If it is a node with a children
Find min value in right subtree
Copy min value to delnode place
Delete the duplicate and stop.
4.Stop
PROGRAM
#include <stdio.h>
#include <stdlib.h>
struct node
{
int key;
struct node *left;
struct node *right;
};
else
{
if (root->left == NULL)
{
temp = root->right;
free(root);
return temp;
}
else if (root->right == NULL)
{
temp = root->left;
free(root);
return temp;
}
temp = minValueNode(root->right);
root->key = temp->key;
root->right = deleteNode(root->right, temp->key);
}
return root;
}
Void main()
{
Struct node *root = NULL;
root = insert(root, 50);
root = insert(root, 30);
root = insert(root, 20);
root = insert(root, 40);
root = insert(root, 70);
root = insert(root, 60);
root = insert(root, 80);
printf("Inorder traversal of the given tree \n");
inorder(root);
printf("\nDelete 20\n");
root = deleteNode(root, 20);
printf("Inorder traversal of the modified tree \n");
inorder(root);
printf("\nDelete 30\n");
root = deleteNode(root, 30);
printf("Inorder traversal of the modified tree \n");
inorder(root);
printf("\nDelete 50\n");
root = deleteNode(root, 50);
printf("Inorder traversal of the modified tree \n");
inorder(root);
}
OUTPUT
Inorder traversal of the given tree 20 30 40 50 60 70 80
Delete 20
Inorder traversal of the modified tree
30 40 50 60 70 80
Delete 30
Inorder traversal of the modified tree
40 50 60 70 80
Delete 50
Inorder traversal of the modified tree 40 60 70 80
RESULT
Thus nodes were inserted and deleted from a binary search tree.
Ex. No. 7 Implementation of AVL Tree
Date:
AIM
To perform insertion operation on an AVL tree and to maintain balance factor.
ALGORITHM
1. Start
2. Perform standard BST insert for w
3. Starting from w, travel up and find the first unbalanced node. Let z be
the first unbalanced node, y be the child of z that comes on the path from
w to z and x be the grandchild of z that comes on the path from w to z.
4. Re-balance the tree by performing appropriate rotations on the subtree
rooted with z. There can be 4 possible cases that needs to be handled as x, y and
z can be arranged in 4 ways.
a) y is left child of z and x is left child of y (Left Left Case)
b) y is left child of z and x is right child of y (Left Right Case)
c) y is right child of z and x is right child of y (Right Right Case)
d) y is right child of z and x is left child of y (Right Left Case)
5.Stop
PROGRAM
/* AVL Tree */
#include <stdio.h>
#include <conio.h>
#include <malloc.h>
#include <stdlib.h>
#define CHANGED 0
#define BALANCED 1
int height;
void displaymenu()
{
printf("\nBasic Operations in AVL tree");
printf("\n0.Display menu list"); printf("\n1.Insert a node in
AVL tree"); printf("\n2.View AVL tree");
printf("\n3.Exit");
}
node* getnode()
{
int size;
p = a;
*pptr = p;
*aptr = a;
}
p->bfactor = -1;
else
p->bfactor = 0;
if(b->bfactor == -1)
a->bfactor = 1;
else
a->bfactor = 1;
b->bfactor = 0;
p = b; *pptr = p; *aptr = a;
*bptr = b;
}
void righttoright(node **pptr, node **aptr)
{
node *p = *pptr, *a = *aptr;
printf("\nRight to Right AVL rotation");
p->right = a->left;
a->left = p;
if(a->bfactor == 0)
{
p->bfactor = -1;
a->bfactor = 1;
height = BALANCED;
}
else
{
p->bfactor = 0;
a->bfactor = 0;
}
p = a;
*pptr = p;
*aptr = a;
}
void righttoleft(node **pptr, node **aptr, node **bptr)
{
node *p = *pptr, *a = *aptr, *b = *bptr;
printf("\nRight to Left AVL rotation");
b = a->left;
a->left = b->right;
b->right = a;
p->right = b->left;
b->left = p;
if(b->bfactor == -1)
p->bfactor = 1;
else
p->bfactor = 0;
if(b->bfactor == -1)
a->bfactor = 0;
b->bfactor = 0;
p = b;
*pptr = p;
*aptr = a;
*bptr = b;
}
void inorder(node *root)
{
if(root == NULL)
return;
inorder(root->left);
printf("\n%4d", root->data);
inorder(root->right);
}
void view(node *root, int level)
{
int k;
if(root == NULL)
return;
view(root->right, level+1);
printf("\n");
for(k=0; k<level; k++)
printf(" ");
printf("%d", root->data);
view(root->left, level+1);
}
switch(p->bfactor)
{
case -1:
p->bfactor = 0;
height = BALANCED;
break;
case 0:
p->bfactor = 1;
break;
case 1:
a = p->left;
if(a->bfactor == 1)
lefttoleft(&p, &a);
else
lefttoright(&p, &a, &b);
height = BALANCED;
break;
}
}
}
if(height== CHANGED)
{
switch(p->bfactor)
{
case -1:
p->bfactor = 0;
height = BALANCED;
break;
case 0:
p->bfactor =-1;
break;
case 1:
a=p->right;
if(a->bfactor == -1)
righttoright(&p, &a);
else
righttoleft(&p, &a, &b);
height=BALANCED;
break;
}
}
}
return(p);
}
main()
{
case 0:
displaymenu();
break;
case 1:
printf(“Enter the value to be inserted “);
scanf(“%d”,&data);
if(searchnode(root,data)==NULL)
root = insertnode(data,root);
else
printf(“\nData already exists “);
break;
case 2:
if(root == NULL)
{
printf("\nAVL tree is empty");
continue;
}
printf("\nInorder traversal of AVL tree");
inorder(root);
printf("\nAVL tree is");
view(root, 1);
break;
case 3:
releasenode(root);
exit(0);
}
}
getch();
}
OUTPUT
AVL tree is
8
7
6
5
4
3
2
1
Enter your choice: 3
RESULT
AIM:
ALGORITHM:
PROGRAM:
#include<stdio.h>
#include<math.h>
#define MAX 100
void swap(int*, int*);
void display(int[],int);
void insert(int[],int,int,int);
int del_hi_priori(int[],int,int);
int main()
{
int lb,choice,num,n,a[MAX],data,s;
choice = 0;
n=0;
lb=0;
while(choice != 4)
{
printf(".....MAIN MENU .......... \n");
printf("\n1.Insert.\n");
printf("2.Delete.\n");
printf("3.Display.\n");
printf("4.Quit.\n"); printf("\nEnter
your choice : ");
scanf("%d",&choice);
switch(choice)
{
case 1:
printf("Enter data to be inserted : ");
scanf("%d",&data);
insert(a,n,data,lb);
n++;
break;
case 2:
s=del_hi_priori(a,n+1,lb);
if(s!=0)
printf("The deleted value is : %d",s);
if(n>0)
n--;
break;
case 3:
printf("\n");
display(a,n);
break;
case 4:
return 0;
default:
printf("Invalid choice\n");
}
printf("\n\n");
}
return 0;
}
// INSERT
void insert(int a[],int heapsize,int data,int lb)
{
int i,p;
int parent(int);
if(heapsize==MAX)
{
printf("Queue Is Full!!n");
return;
}
i=lb+heapsize;
a[i]=data;
while(i>lb&&a[p=parent(i)]<a[i])
{
swap(&a[p],&a[i]);
i=p;
}
}
// DELETE
int del_hi_priori(int a[],int heapsize,int lb)
{
int data,i,l,r,max_child,t;
int left(int);
int right(int);
if(heapsize==1)
{
printf("Queue Is Empty!!\n");
return 0;
}
t=a[lb]; swap(&a[lb],&a[heapsize-
1]); i=lb;
heapsize--;
while(1)
{
if((l=left(i))>=heapsize)
break;
if((r=right(i))>=heapsize)
max_child=l;
else
max_child=(a[l]>a[r])?l:r;
if(a[i]>=a[max_child]) break;
swap(&a[i],&a[max_child]);
i=max_child;
}
return t;
}
//Returns Parent Index
int parent(int i)
{
float p;
p=((float)i/2.0)-1.0;
return ceil(p);
}
//Return Leftchild Index
int left(int i)
{
return 2*i+1;
}
//Return Rightchild Index
int right(int i)
{
return 2*i+2;
}
//-------DISPLAY-------
void display(int a[],int n)
{
int i;
if(n==0)
{
printf("Queue Is Empty!!\n");
return;
}
for(i=0;i<n;i++)
printf("%d ",a[i]);
printf("\n");
}
// SWAP
void swap(int*p,int*q)
{
int temp;
temp=*p;
*p=*q;
*q=temp;
}
OUTPUT:
.....Main Menu.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your Choice:3
Queue is Empty!!
.....Main Menu.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your Choice:1
Enter Data to be inserted: 100
.....Main Menu.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your Choice: 2
the deleted value is : 100
.....Main Menu.....
1.Insert.
2.Delete.
3.Display.
4.Quit.
Enter your Choice:4
RESULT:
Thus, the Priority Queue using Binary Heap is implemented and the result is verified successfully.
Ex. No. 9 Implementation of Dijkstra’s Algorithm
Date:
Aim
To find the shortest path for the given graph from a specified source to all other
vertices using Dijkstra’s algorithm
Algorithm
1. Start
2. Obtain no. of vertices and adjacency matrix for the given graph
3. Create cost matrix from adjacency matrix. C[i][j] is the cost of
going from vertex i to vertex j. If there is no edge between vertices i
and j then C[i][j] is infinity
4. Initialize visited[] to zero
5. Read source vertex and mark it as visited
6. Create the distance matrix, by storing the cost of vertices from vertex no. 0
to n-1 from the source vertex
distance[i]=cost[0][i];
Choose a vertex w, such that distance[w] is minimum and visited[w] is 0. Mark
visited[w] as 1.
7. Recalculate the shortest distance of remaining vertices from the source.
8. Only, the vertices not marked as 1 in array visited[ ] should be
considered for recalculation of distance. i.e. for each vertex v
if(visited[v]==0)
distance[v]=min(distance[v]
distance[w]+cost[w][v])
9. Stop
Program
/* Dijkstra’s Shortest Path */
#include <stdio.h>
#include <conio.h>
#define INFINITY 9999
#define MAX 10
void dijkstra(int G[MAX][MAX], int n, int startnode);
main()
{
int G[MAX][MAX], i, j, n, u;
printf("Enter no. of vertices: ");
scanf("%d", &n); printf("Enter the adjacency matrix:\n");
for(i=0; i<n; i++)
for(j=0; j<n; j++)
scanf("%d", &G[i][j]);
printf("Enter the starting node: ");
scanf("%d", &u);
dijkstra(G, n, u);
}
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;
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];
for(i=0; i<n; i++)
{
distance[i] = cost[startnode][i];
pred[i] = startnode;
visited[i] = 0;
}
distance[startnode] = 0;
visited[startnode] = 1;
count = 1; while(count < n-1)
{
mindistance =INFINITY;
for(i=0; i<n;i++)
if(distance[i]< mindistance && !visited[i])
{
mindistance = distance[i];
nextnode=i;
}
visited[nextnode] = 1;
for(i=0; i<n; i++)
if(!visited[i])
if(mindistance + cost[nextnode][i] < distance[i])
{
count++;
}
for(i=0; i<n; i++)
if(i != startnode)
{
printf("\nDistance to node%d = %d", i, distance[i]);
printf("\nPath = %d", i);j = i;
do
{
j = pred[j]; printf("<-%d", j);
} while(j != startnode);
}
}
Output
Enter no. of vertices: 5
Enter the adjacency
matrix:
0 10 0 30 100
10 0 50 0 0
0 50 0 20 10
30 0 20 0 60
100 0 0 60 0
Enter the starting node: 0
Distance to node1 = 10
Path = 1<-0
Distance to node2 = 50
Path = 2<-3<-0
Distance to node3 = 30
Path = 3<-0
Distance to node4= 60
Path = 4<-2<-3<-0
Result
Thus Dijkstra's algorithm is used to find shortest path from a given vertex.
Ex. No:10 Implementation of Prim’s Algorithm
Date:
Aim
Algorithm
Step 3: Select an edge 'e' connecting the tree vertex and fringe vertex that has minimum weight
Step 4: Add the selected edge and the vertex to the minimum spanning tree T
[END OF LOOP]
Step 5: EXIT
Program
#include<stdio.h>
#include<conio.h> int
a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
printf("\nEnter the number of nodes:");
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;
}
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,b,min); mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
getch();
}
Output
Result
Thus the C program for the implementation of Prim’s algorithm is executed successfully.
Ex. No. 11a Implementation of Searching-Linear Search
Date:
Aim
To perform linear search of an element on the given array.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai, i = 0,1,2,…n–1
4. Read search value
5. Assign 0 to found
6. Check each array element against search
If Ai = search then
found = 1
Print "Element
found" Print position
i
Stop
7. If found = 0 then
print "Element not found"
8. Stop
Program
#include
<stdio.h>
#include
<conio.h> main()
{
int a[50],i, n, val, found;
clrscr();
printf("Enter number of elements : ");
scanf("%d", &n); printf("Enter Array Elements : \n");
for(i=0; i<n;i++)
scanf("%d", &a[i]);
printf("Enter element to locate : ");
scanf("%d", &val);
found = 0;
for(i=0; i<n;
i++)
{
if (a[i] == val)
{
printf("Element found at position %d",i);
found = 1;
break;
}
}
if (found == 0)
printf("\n Element not found");
getch();
}
Output
Result
Aim
To locate an element in a sorted array using Binary search method
Algorithm
1. Start
2. Read number of array elements, say n
3. Create an array arr consisting n sorted elements
4. Get element, say key to be located
5. Assign 0 to lower and n to upper
6. While (lower < upper)
Determine middle element mid =
(upper+lower)/2 If key = arr[mid] then
Print
mid Stop
Else if key > arr[mid] then
lower = mid + 1
else
upper = mid – 1
#include <stdio.h>
#include <conio.h>
main()
{
int a[50],i, n, upper, lower, mid, val, found; clrscr();
if (found == -1)
printf("Element not
found"); getch();
}
Out put
Result
Aim
To sort an array of N numbers using Insertion sort.
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Sort the elements using insertion sort
In pass p, move the element in position p left until its correct place is
foundamong the first p + 1 elements.
Element at position p is saved in temp, and all larger elements
(prior to position p) are moved one spot to the right. Then temp
is placed in the correct spot.
5. Stop
Program
/* Insertion Sort */
main()
{
int i, j, k, n, temp, a[20], p=0;
printf("Enter totalelements");
scanf("%d",&n);
printf("Enter array
elements:");
for(i=0; i<n; i++)
scanf("%d", &a[i]);
for(i=1; i<n; i++)
{
temp=a[i];
j = i-1;
while((temp<a[j]) && (j>=0))
{
a[j+1] =a[j];
j = j - 1;
}
a[j+1] = temp;
p++;
printf("\n After Pass%d:",p);
for(k=0; k<n; k++)
printf("%d", a[k]);
}
Output
Result
Aim
Algorithm
Step 3 – swap the first location with the minimum value in the array
#include <stdio.h>
void SelSort(int array[],int n);
int main()
{
int array[100], n,i;
printf("Enter number of elements");
scanf("%d", &n);
printf("Enter %d Numbers", n);
for(i = 0; i < n; i++) scanf("%d",
&array[i]); SelSort(array,n);
return 0;
}
void SelSort(int array[], int n)
{
int i, j, position, swap; for(i
= 0; i < (n - 1); i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(array[position]>array[j]) position=j;
}
if(position != i)
{
swap=array[i]; array[i]=array[position];
array[position]=swap;
}
}
printf("Sorted Array:");
for(i = 0; i < n; i++)
printf("%d ", array[i]);
}
Output
Result
Thus the C program for the selection sort has been performed successfully.
Ex. No. 13 Implementation of Sorting- Merge Sort
Date:
Aim
Algorithm
1. Start
2. Read number of array elements n
3. Read array elements Ai
4. Divide the array into sub-arrays with a set of elements
5. Recursively sort the sub-arrays
6. Merge the sorted sub-arrays onto a single sorted array.
7. Stop
Program
/* Merge sort */
#include <stdio.h>
#include <conio.h>
main()
{
int i, arr[30];
printf("Enter total no. of elements : ");
scanf("%d", &size);
printf("Enter array elements : ");
for(i=0; i<size; i++)
scanf("%d", &arr[i]);
part(arr, 0, size-1);
printf("\n Merge sorted list : ");
for(i=0; i<size; i++)
printf("%d ",arr[i]);
getch();
}
if (max-min == (size/2)-1)
{
printf("\n Half sorted list : ");
for(i=min; i<=max; i++)
Result
Thus array elements was sorted using merge sort's divide and conquer method.
Ex. No. 14a Implementation of Hashing- Open addressing with linear probing
Date:
Aim
To implement hashing with linear probing.
Algorithm:
1. Create a structure, data (hash table item) with key and value as data.
2. Now create an array of structure, data of some certain size (10, in this case). But, the
size of array must be immediately updated to a prime number just greater than initial
array capacity (i.e 10, in this case).
3. A menu is displayed on the screen.
4. User must choose one option from four choices given in the menu
5. Perform all the operations
6. Stop
Program:
/* Open hashing */
#include
<stdio.h>
#include
<stdlib.h>
#define MAX 1
main()
{
int a[MAX], num, key, i;
char ans;
int create(int);
void linearprobing(int[], int, int);
void display(int[]);
printf("\nCollision handling by linear probing\n\n");
for(i=0; i<MAX; i++)
a[i] = -1;
do
{
printf("\n Enter
number:"); scanf("%d",
&num);
key = create(num);
linearprobing(a, key, num);
printf("\nwish to
continue?(y/n):"); ans = getch();
} while( ans == 'y');
display(a);
}
int create(int num)
{
int key;
key = num %10;
return key;
}
Output:
Result
Thus the C program for the hashing has been performed successfully.
Ex.No:14b IMPLEMENTATION OF OPEN ADDRESSING WITH
Date: QUADRATIC PROBING
AIM:
ALGORITHM:
Hashtable is an array of size = tsize
Step 1:c o m p u t e t h e h a s h k e y u s i n g m o d
f u n c t i o n Step 2:let i = 0
Step 3:k e y = n u m % t s i z e .
Step 4: compute the index at which the value has to be inserted in hash table
index = (key+ i * i) % tsize
Step 5: if there is no element at that index then insert the value at index and STOP
PROGRAM:
#include<stdio.h>
#include<conio.h>
int main()
{
int Size =10;
int num;
int hash_table[size];
char ans;
for(int i=0;i<size;i++)
{
hash_table[i]=-1;
}
do
{
Printf(“\n enter the number:”);
Scanf(“%d”,&num);
Quadratic_prob(hash_table,size,num);
Printf(“\n Do u wish to continue?(Y/n)”);
ans=getch();
}while(ans==’y’);
return 0;
}
OUTPUT
0 -1
1 -1
2 -1
3 -1
4 -1
5 -1
6 -1
7 37
8 -1
9 -1
Do u wish to continue?(y/n)
0 90
1 -1
2 -1
3 -1
4 -1
5 -1
6 -1
7 -1
8 -1
9 -1
Do u wish to continue?(y/n)
RESULT: