Data Structure
Data Structure
AIM:
To implement stack using array in C.
ALGORITHM:
1: Include all the header files and give the maximum size.
2: Define a integer variable 'top' and initialize with '-1'. (int top = -1).
3: Create a one dimensional array „a‟ with max size.
4: Display the menu with list of operations and perform the operation selected by the user on the
stack.
5: Operations:
push - to insert an element into the stack.
pop - to delete an element from the stack
display – to display the elements of a stack.
Exit – to exit from the program
PROGRAM:
#include<stdio.h>
void main()
{
int a[10]={0},i,top=-1,max=10,n,x;
printf("\n\tMENU\n1.PUSH\n2.POP\n3.DISPLAY\n4.EXIT\n");
do
{
printf("\nEnter your choice\n");
scanf("%d",&n);
switch(n)
{
case 1:
if(top==max-1)
printf("Stack is FULL\n");
else
{
printf("Enter the element\n");
scanf("%d",&x);
a[++top]=x;
}
break;
case 2:
if(top<0)
printf("Stack is Empty\n");
else
printf("The deleted item =%d",a[top--]); break;
case 3:
if(top<0)
printf("The stack is empty\n");
else
{
printf("The elements of the stack are :");
for(i=0;i<=top;i++)
printf("%d\n",a[i]);
}
break;
case 4:
break;
default:
printf("Invalid choice\n");
break;
}
}
while(n!=4);
}
OUTPUT:
MENU
1.PUSH
2. POP
3. DISPLAY
4. EXIT
Enter your choice
1
Enter the element
2
Enter your choice
1
Enter the element
3
Enter your choice
2
The deleted item =3
Enter your choice
3
The elements of the stack are :2
Enter your choice
4
RESULT:
Thus, the program to implement stack using array in C was executed successfully.
Ex.no:1b ARRAY IMPLEMENTATION OF QUEUE
AIM:
To implement Queue using array in C.
ALGORITHM:
1: Include all the header files and define the maximum size.
2: Create a one dimensional array „queue_array‟ with max size.
3: Define the integer variables 'rear' and „front‟ and initialize them with '-1'.
4: Display the menu with list of operations and perform the operation selected by the user on the
Queue.
5: Operations:
enQueue- to insert an element into the Queue.
deQueue - to delete an element from the Queue
display – to display the elements of a Queue.
exit – to exit from the program
PROGRAM:
#include <stdio.h>
#define MAX 50
int queue_array[MAX];
int rear = - 1;
int front = - 1;
void main()
{
int choice;
while (1)
{
printf("1.Insert element to queue \n");
printf("2.Delete element from queue \n");
printf("3.Display all elements of queue \n");
printf("4.Quit \n");
printf("Enter your choice : ");
scanf("%d", &choice);
switch (choice)
{
case 1:
insert();
break;
case 2:
delete();
break;
case 3:
display();
break;
case 4:
exit(1);
default:
printf("Wrong choice \n");
} /*End of switch*/
} /*End of while*/
} /*End of main()*/
insert()
{
int add_item;
if (rear == MAX - 1)
printf("Queue Overflow \n");
else
{
if (front == - 1)
/*If queue is initially empty */
front = 0;
printf("Inset the element in queue : ");
scanf("%d", &add_item);
rear = rear + 1;
queue_array[rear] = add_item;
}
} /*End of insert()*/
delete()
{
if (front == - 1 || front > rear)
{
printf("Queue Underflow \n");
return ;
}
else
{
printf("Element deleted from queue is : %d\n", queue_array[front]);
front = front + 1;
}
} /*End of delete() */
display()
{
int i;
if (front == - 1)
printf("Queue is empty \n");
else
{
printf("Queue is : \n");
for (i = front; i <= rear; i++)
printf("%d ", queue_array[i]);
printf("\n");
}
}
OUTPUT:
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 29
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 16
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 1
Inset the element in queue : 4
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 3
Queue is :
29 16 4
1. Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 2
Element deleted from queue is : 29
1.Insert element to queue
2. Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 3
Queue is :
16 4
1.Insert element to queue
2.Delete element from queue
3.Display all elements of queue
4.Quit
Enter your choice : 4
RESULT:
Thus, the program to implement Queue using array in C was executed successfully.
Ex.no:1c ARRAY IMPLEMENTATION OF CIRCULAR QUEUE
AIM:
To write a C program to implement the circular queue using array.
ALGORITHM:
1: Include all the header files and define the maximum size.
2: Create a one dimensional array „queue_array‟ with max size.
3: Define the integer variables 'rear' and „front‟ and initialize them with '-1'.
4: Display the menu with list of operations and perform the operation selected by the user on the
Queue.
5: Operations:
Front - Used to get the starting element of the Circular Queue.
Rear - Used to get the end element of the Circular Queue.
enQueue(value) - Used to insert a new value in the Circular Queue. This operation takes place
from the end of the Queue.
deQueue() - Used to delete a value from the Circular Queue. This operation takes place from
the front of the Queue.
PROGRAM
#include<stdio.h>
# define MAX 5
int cqueue_arr[MAX];
int front = -1;
int rear = -1;
void insert(int item)
{
if((front == 0 && rear == MAX-1) || (front == rear+1))
{
printf("Queue Overflow n");
return;
}
if(front == -1)
{
front = 0;
rear = 0;
}
else
{
if(rear == MAX-1)
rear = 0;
else
rear = rear+1;
}
cqueue_arr[rear] = item ;
}
void deletion()
{
if(front == -1)
{
printf("Queue Underflown");
return ;
}
printf("Element deleted from queue is : %dn",cqueue_arr[front]);
if(front == rear)
{
front = -1;
rear=-1;
}
else
{
if(front == MAX-1)
front = 0;
else
front = front+1;
}
}
void display()
{
int front_pos = front,rear_pos = rear;
if(front == -1)
{
printf("Queue is emptyn");
return;
}
printf("Queue elements :n");
if( front_pos <= rear_pos )
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
else
{
while(front_pos <= MAX-1)
{
printf("%d ",cqueue_arr[front_pos])
front_pos++;
}
front_pos = 0;
while(front_pos <= rear_pos)
{
printf("%d ",cqueue_arr[front_pos]);
front_pos++;
}
}
printf("/n");
}
int main()
{
int choice,item;
do
{
printf("1.Insert\n");
printf("2.Delete\n");
printf("3.Display\n");
printf("4.Quit\n");
printf("Enter your choice :\n ");
scanf("%d",&choice);
switch(choice)
{
case 1 :
printf("Input the element for insertion in queue :\n");
scanf("%d", &item);
insert(item);
break;
case 2 :
deletion();
break;
case 3:
display();
break;
case 4:
break;
default:
printf("Wrong choice\n");
}
}while(choice!=4);
return 0;
}
RESULT:
Thus the C program was written for circular queue implementation and the output was
verified successfully.
Ex.no:2 LINKED LIST IMPLEMENTATION OF LIST
AIM:
To implement List using Linked List in C.
ALGORITHM:
1: Include all the header files.
2: Create a structure LIST with no and *next.
3: Declare all the functions with which operations are done on the linked list.
4: Display the menu with list of operations and perform the operation selected by the user on the
linked List.
5: Operations:
create – to create the linked list
insert- to insert an element into the linked list in the chosen position.
deletion - to delete an element from the chosen position in the linked list
display – to display the elements of the linked List.
exit – to exit from the program
PROGRAM:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<process.h>
#define NULL 0
typedef struct list
{
int no;
struct list *next;
}LIST;
LIST *p,*t,*h,*y,*ptr,*pt;
AIM:
To implement Stack using Linked List in C.
ALGORITHM:
1: Include all the header files.
2: Create a structure node with data and *link.
3: Declare all the functions with which operations are done on the linked list implementation of
stack.
4: Display the menu with list of operations and perform the operation selected by the user on the
linked List implementation of stack.
5: Operations:
Push - to insert an element into the stack.
Pop - to delete an element from the stack.
display – to display the elements of the stack.
exit – to exit from the program
PROGRAM:
#include "stdio.h"
#include "stdlib.h"
#include "conio.h"
void pop();
void push(int value);
void display();
struct node
{
int data;
struct node *link;
};
struct node *top=NULL,*temp;
void main()
{
int choice,data;
printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\n");
printf("\nEnter ur choice:");
scanf("%d",&choice);
switch(choice)
{
case 1: //To push a new element into stack
}
}
void display()
{
temp=top;
if(temp==NULL)
{
printf("\nStack is empty\n");
}
printf("\n The Contents of the Stack are...");
while(temp!=NULL)
{
printf(" %d ->",temp->data);
temp=temp->link;
}
}
void push(int data)
{
temp=(struct node *)malloc(sizeof(struct node)); // creating a space for the new element.
temp->data=data;
temp->link=top;
top=temp;
display();
}
void pop()
{
if(top!=NULL)
{
printf("The poped element is %d",top->data);
top=top->link;
}
else
{
printf("\nStack Underflow");
}
display();
}
OUTPUT:
1. Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
Enter a new element :2
The Contents of the Stack are... 2 ->
1.Push
2. Pop
3.Display
4.Exit
Enter ur choice:1
Enter a new element :5
The Contents of the Stack are... 5 -> 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:1
Enter a new element :9
The Contents of the Stack are... 9 -> 5 -> 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:3
The Contents of the Stack are... 9 -> 5 -> 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:2
The poped element is 9
The Contents of the Stack are... 5 -> 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:2
The poped element is 5
The Contents of the Stack are... 2 ->
1.Push
2.Pop
3.Display
4.Exit
Enter ur choice:4
RESULT:
Thus the program to implement stack ADT using Linked list in C was executed
successfully.
Ex.no:3b LINKED LIST IMPLEMENTATION OF QUEUE
AIM:
To implement Queue using Linked List in C.
ALGORITHM:
Step 1: Include all the header files.
Step 2: Create a structure node with info and *ptr.
Step 3: Declare all the functions with which operations are done on the linked list
implementation of Queue.
Step 4: Display the menu with list of operations and perform the operation selected by the user
on the linked List implementation of Queue.
Step 5: Operations:
enq - to insert an element into the Queue.
deq - to delete an element from the Queue.
display – to display the elements of the Queue.
empty – to check whether the queue is empty
queuesize – to display the size of the Queue
frontelement - to display the element at the front position of the Queue
exit – to exit from the program
PROGRAM:
#include <stdio.h>
#include <stdlib.h>
struct node
{
int info;
struct node *ptr;
}*front,*rear,*temp,*front1;
int frontelement();
void enq(int data);
void deq();
void empty();
void display();
void create();
void queuesize();
int count = 0;
void main()
{
int no, ch, e;
clrscr();
printf("\n 1 - Enque");
printf("\n 2 - Deque");
printf("\n 3 - Front element");
printf("\n 4 - Empty");
printf("\n 5 - Queue size");
printf("\n 6 - Display");
printf("\n 7 - Exit");
create();
while (1)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
enq(no);
break;
case 2:
deq();
break;
case 3:
e = frontelement();
if (e != 0)
printf("Front element : %d", e);
else
printf("\n No front element in Queue as queue is empty");
break;
case 4:
empty();
break;
case 5:
queuesize();
break;
case 6:
display();
break;
case 7:
exit(0);
default:
printf("Wrong choice, Please enter correct choice ");
break;
}
}
}
/* Create an empty queue */
void create()
{
front = rear = NULL;
}
/* Returns queue size */
void queuesize()
{
printf("\n Queue size : %d", count);
}
/* Enqueing the queue */
void enq(int data)
{
if (rear == NULL)
{
rear = (struct node *)malloc(1*sizeof(struct node));
rear->ptr = NULL;
rear->info = data;
front = rear;
}
else
{
temp=(struct node *)malloc(1*sizeof(struct node));
rear->ptr = temp;
temp->info = data;
temp->ptr = NULL;
rear = temp;
}
count++;
}
/* Displaying the queue elements */
void display()
{
front1 = front;
if ((front1 == NULL) && (rear == NULL))
{
printf("Queue is empty");
return;
}
while (front1 != rear)
{
printf("%d ", front1->info);
front1 = front1->ptr;
}
if (front1 == rear)
printf("%d", front1->info);
}
/* Dequeing the queue */
void deq()
{
front1 = front;
if (front1 == NULL)
{
printf("\n Error: Trying to display elements from empty queue");
return;
}
else
if (front1->ptr != NULL)
{
front1 = front1->ptr;
printf("\n Dequed value : %d", front->info);
free(front);
front = front1;
}
else
{
printf("\n Dequed value : %d", front->info);
free(front);
front = NULL;
rear = NULL;
}
count--;
}
/* Returns the front element of queue */
int frontelement()
{
if ((front != NULL) && (rear != NULL))
return(front->info);
else
return 0;
}
/* Display if queue is empty or not */
void empty()
{
if ((front == NULL) && (rear == NULL))
printf("\n Queue empty");
else
printf("Queue not empty");
}
OUTPUT:
1 - Enque
2 - Deque
3 - Front element
4 - Empty
5 - Queue size
6 - Display
7 - Exit
Enter choice : 1
Enter data : 4
Enter choice : 1
Enter data : 5
Enter choice : 1
Enter data : 6
Enter choice : 1
Enter data : 7
Enter choice : 2
Dequed value : 4
Enter choice : 6
567
Enter choice : 3
Front element : 5
Enter choice : 4
Queue not empty
Enter choice : 5
Queue size : 3
Enter choice : 6
567
Enter choice : 7
RESULT:
Thus, the program to implement Queue ADT using Linked list in C was executed
successfully.
Ex.no:4. POLYNOMIAL MANIPULATION USING LINKED LIST
AIM:
To write a C program to add two polynomials.
ALGORITHM:
1. Read the two polynomials to perform addition
2. if exponent terms are common then the two polynomials will be added together
3. if nothing is common then the size of this polynomial is = total no. of terms of 1st polynomial + total
number of terms of 2nd polynomial.
PROGRAM:
#include<stdio.h>
/* declare structure for polynomial */
struct poly
{
int coeff;
int expo;
};
/* declare three arrays p1, p2, p3 of type structure poly.
* each polynomial can have maximum of ten terms
* addition result of p1 and p2 is stored in p3 */
struct poly p1[10],p2[10],p3[10];
/* function prototypes */
int readPoly(struct poly []);
int addPoly(struct poly [],struct poly [],int ,int ,struct poly []);
void displayPoly( struct poly [],int terms);
int main()
{
int t1,t2,t3;
int addPoly(struct poly p1[10],struct poly p2[10],int t1,int t2,struct poly p3[10])
{
int i,j,k;
i=0;
j=0;
k=0;
while(i<t1 && j<t2)
{
if(p1[i].expo==p2[j].expo)
{
p3[k].coeff=p1[i].coeff + p2[j].coeff;
p3[k].expo=p1[i].expo;
i++;
j++;
k++;
}
else if(p1[i].expo>p2[j].expo)
{ p3[k].coeff=p1[i].coeff;
p3[k].expo=p1[i].expo;
i++;
k++;
}
else
{
p3[k].coeff=p2[j].coeff;
p3[k].expo=p2[j].expo;
j++;
k++;
}
}
/* for rest over terms of polynomial 1 */
while(i<t1)
{
p3[k].coeff=p1[i].coeff;
p3[k].expo=p1[i].expo;
i++;
k++;
}
/* for rest over terms of polynomial 2 */
while(j<t2)
{
p3[k].coeff=p2[j].coeff;
p3[k].expo=p2[j].expo;
j++;
k++;
}
return(k); /* k is number of terms in resultant polynomial*/
}
RESULT:
Thus the C program is written to add two polynomials successfully.
Ex.no:5a EVALUATION OF POSTFIX EXPRESSIONS
AIM:
To wtite a C program to evaluate the postfix expression.
ALGORITHM
1: If a character is an operand push it to Stack
2: If the character is an operator Pop two elements from the Stack.
Operate on these elements according to the operator, and push the result back to the Stack.
3: Step 1 and 2 will be repeated until the end has reached.
4: The Result is stored at the top of the Stack,return it
5: End
PROGRAM:
#include<stdio.h>
int stack[20];
int top = -1;
void push(int x)
{
stack[++top] = x;
}
int pop()
{
return stack[top--];
}
int main()
{
char exp[20];
char *e;
int n1,n2,n3,num;
printf("Enter the expression :: ");
scanf("%s",exp);
e = exp;
while(*e != '\0')
{
if(isdigit(*e))
{
num = *e - 48;
push(num);
}
else
{
n1 = pop();
n2 = pop();
switch(*e)
{
case '+':
{
n3 = n1 + n2;
break;
}
case '-':
{
n3 = n2 - n1;
break;
}
case '*':
{
n3 = n1 * n2;
break;
}
case '/':
{
n3 = n2 / n1;
break;
}
}
push(n3);
}
e++;
}
printf("\nThe result of expression %s = %d\n\n",exp,pop());
return 0;
}
OUTPUT:
Enter the expression :: 245+*
The result of expression 245+* = 18
RESULT:
Thus the C program is written to evaluate the postfix expression successfully.
Ex.no:5b INFIX TO POSTFIX
AIM:
To write a C program to convert infix expression on to postfix expression.
ALGORITHM
1: If the scanned character is an operand, put it into postfix expression.
2: If the scanned character is an operator and operator's stack is empty, push operator into
operators' stack.
3: If the operator's stack is not empty, there may be following possibilities.
If the precedence of scanned operator is greater than the top most operator of
operator's stack, push this operator into operator 's stack.
If the precedence of scanned operator is less than the top most operator of
operator's stack, pop the operators from operator's stack until we find a low
precedence operator than the scanned character.
If the precedence of scanned operator is equal then check the associativity of the
operator. If associativity left to right then pop the operators from stack until we
find a low precedence operator. If associativity right to left then simply put into
stack.
If the scanned character is opening round bracket ( '(' ), push it into operator's
stack.
If the scanned character is closing round bracket ( ')' ), pop out operators from
operator's stack until we find an opening bracket ('(' ).
4:Repeat Step 1,2 and 3 till expression has character
5: Now pop out all the remaining operators from the operator's stack and push into postfix
expression.
6: Exit
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--];
}
int priority(char x)
{
if(x == '(')
return 0;
if(x == '+' || x == '-')
return 1;
if(x == '*' || x == '/')
return 2;
return 0;
}
int main()
{
char exp[100];
char *e, x;
printf("Enter the expression : ");
scanf("%s",exp);
printf("\n");
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;
}
OUTPUT:
Enter the expression :
a+b
ab+
RESULT:
Thus the C program is written to convert infix expression into post fix expression
successfully.
Ex.no:6 IMPLEMENTATION OF BINARY SEARCH TREES
AIM:
To implement the operations in Binary Search Tree using C.
ALGORITHM:
1: Create the binary search tree
2: Declare all the functions with which operations are done on the Binary search tree.
3: Display the menu with list of operations and perform the operation selected by the user on the
Binary search tree.
4: Operations
Insert – to insert an element into the Binary search tree
Delete - to delete an element from the Binary search tree
Display – to display the elements of the Binary search tree
Search – to search an element from the Binary search tree
exit – to exit from the program
PROGRAM:
#include<stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];
printf("Enter number of elements:\n");
scanf("%d",&n);
printf("Enter %d integers:\n", n);
for (c = 0; c < n; c++)
scanf("%d",&array[c]);
printf("Enter the value to find:\n");
scanf("%d", &search);
first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last) {
if (array[middle] < search)
first = middle + 1;
else if (array[middle] == search) {
printf("%d is present at index %d.\n", search, middle+1);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Not found! %d is not present in the list.\n", search);
return 0;
getch();
}
OUTPUT:
Enter number of elements:
5
Enter 5 integers:
1
9
22
24
46
Enter the value to find:
24
24 is present at index 4.
RESULT:
Thus, the program to implement the operations in Binary Search Tree in C was executed
successfully.
Ex.no:7 IMPLEMENTATION OF AVL TREES
AIM:
To implement the operations in AVL Tree using C.
ALGORITHM:
1: Create the AVL tree.
2: Declare all the functions with which operations are done on the AVL tree.
3: Display the menu with list of operations and perform the operation selected by the user on the
AVL tree.
4: Operations
Insert – to insert an element into the AVL tree.
Delete - to delete an element from the AVL tree.
Print – to display the elements of the AVL tree.
exit – to exit from the program
PROGRAM:
#include<stdio.h>
typedef struct node
{
int data;
struct node *left,*right;
int ht;
}node;
node *insert(node *,int);
node *Delete(node *,int);
void preorder(node *);
void inorder(node *);
int height( node *);
node *rotateright(node *);
node *rotateleft(node *);
node *RR(node *);
node *LL(node *);
node *LR(node *);
node *RL(node *);
int BF(node *);
int main()
{
node *root=NULL;
int x,n,i,op;
do
{
printf("\n1)Create:");
printf("\n2)Insert:");
printf("\n3)Delete:");
printf("\n4)Print:");
printf("\n5)Quit:");
printf("\n\nEnter Your Choice:");
scanf("%d",&op);
switch(op)
{
case 1: printf("\nEnter no. of elements:");
scanf("%d",&n);
printf("\nEnter tree data:");
root=NULL;
for(i=0;i<n;i++)
{
scanf("%d",&x);
root=insert(root,x);
}
break;
case 2: printf("\nEnter a data:");
scanf("%d",&x);
root=insert(root,x);
break;
return(T);
}
while(p->left!= NULL)
p=p->left;
T->data=p->data;
T->right=Delete(T->right,p->data);
if(BF(T)==2)//Rebalance during windup
if(BF(T->left)>=0)
T=LL(T);
else
T=LR(T);\
}
else
return(T->left);
}
T->ht=height(T);
return(T);
}
int height(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
if(lh>rh)
return(lh);
return(rh);
}
return(T);
}
node * RL(node *T)
{
T->right=rotateright(T->right);
T=rotateleft(T);
return(T);
}
int BF(node *T)
{
int lh,rh;
if(T==NULL)
return(0);
if(T->left==NULL)
lh=0;
else
lh=1+T->left->ht;
if(T->right==NULL)
rh=0;
else
rh=1+T->right->ht;
return(lh-rh);
}
void preorder(node *T)
{
if(T!=NULL)
{
printf("%d(Bf=%d)",T->data,BF(T));
preorder(T->left);
preorder(T->right);
}
}
void inorder(node *T)
{
if(T!=NULL)
{
inorder(T->left);
printf("%d(Bf=%d)",T->data,BF(T));
inorder(T->right);
}
}
OUTPUT:
1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
Enter Your Choice:1
Enter no. of elements:4
Enter tree data:7 12 4 9
1)Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
Enter Your Choice:4
Preorder sequence:
7(Bf=-1)4(Bf=0)12(Bf=1)9(Bf=0)
Inorder sequence:
4(Bf=0)7(Bf=-1)9(Bf=0)12(Bf=1)
1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
Enter Your Choice:3
Enter a data:7
1)Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
Enter Your Choice:4
Preorder sequence:
9(Bf=0)4(Bf=0)12(Bf=0)
Inorder sequence:
4(Bf=0)9(Bf=0)12(Bf=0)
1) Create:
2) Insert:
3) Delete:
4) Print:
5) Quit:
Enter Your Choice:5
RESULT:
Thus, the program to implement the operations in AVL Tree in C was executed
successfully.
Ex.no:8 IMPLEMENTATION OF HEAPS USING PRIORITY QUEUE
AIM:
To implement the Heap using Priority Queue in C.
ALGORITHM:
1: Create the heap using Priority Queue.
2: Declare all the functions with which operations are done on the Priority Queue.
3: Display the menu with list of operations and perform the operation selected by the user on the
Priority Queue.
4: Operations
Insert – to insert an element into the Priority Queue.
Delete - to delete an element from the Priority Queue.
Display – to display the elements of the Priority Queue.
exit – to exit from the program
PROGRAM:
#include<stdio.h>
#include<malloc.h>
void insert();
void del();
void display();
struct node
{
int priority;
int info;
struct node *next;
}*start=NULL,*q,*temp,*new;
typedef struct node N;
void main()
{
int ch;
clrscr();
do
{
printf("\n[1] INSERTION\t[2] DELETION\t[3] DISPLAY [4] EXIT\t:");
scanf("%d",&ch);
switch(ch)
{
case 1:insert();
break;
case 2:del();
break;
case 3:display();
break;
case 4:
break;
}
}
while(ch<4);
}
void insert()
{
int item,itprio;
new=(N*)malloc(sizeof(N));
printf("ENTER THE ELT.TO BE INSERTED :\t");
scanf("%d",&item);
printf("ENTER ITS PRIORITY :\t");
scanf("%d",&itprio);
new->info=item;
new->priority=itprio;
new->next=NULL;
if(start==NULL )
{
//new->next=start;
start=new;
}
else if(start!=NULL&&itprio<=start->priority)
{ new->next=start;
start=new;
}
else
{
q=start;
while(q->next != NULL && q->next->priority<=itprio)
{q=q->next;}
new->next=q->next;
q->next=new;
}
}
void del()
{
if(start==NULL)
{
printf("\nQUEUE UNDERFLOW\n");
}
else
{
new=start;
printf("\nDELETED ITEM IS %d\n",new->info);
start=start->next;
//free(start);
}
}
void display()
{
temp=start;
if(start==NULL)
printf("QUEUE IS EMPTY\n");
else
{
printf("QUEUE IS:\n");
if(temp!=NULL)
for(temp=start;temp!=NULL;temp=temp->next)
{
printf("\n%d priority =%d\n",temp->info,temp->priority);
//temp=temp->next;
}
}
}
OUTPUT:
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :1
ENTER THE ELT.TO BE INSERTED : 2
ENTER ITS PRIORITY : 1
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :1
ENTER THE ELT.TO BE INSERTED : 3
ENTER ITS PRIORITY : 2
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :3
QUEUE IS:
2 priority =1
3 priority =2
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :2
DELETED ITEM IS 2
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :3
QUEUE IS:
3 priority =2
[1] INSERTION [2] DELETION [3] DISPLAY [4] EXIT :4
RESULT:
Thus, the program to implement the Heap using Priority Queue in C was executed
successfully.
Ex. No: 9 IMPLEMENTATION OF DIJIKSTRA’S ALGORITHM
AIM:
To write a program to implementation of Dijkstra‟s algorithm.
ALGORITHM:
1. start the program
2. Initialize the required variables
3. Assign to every node a distance value. Set it to zero for our initial node and to infinity for all
other nodes.
4. Mark all nodes as unvisited. Set initial node as current.
5. For current node, consider all its unvisited neighbors and calculate their distance (from the
initial node). For example, if current node (A) has distance of 6, and an edge connecting it with
another node (B) is 2, the distance to B through A will be 6+2=8. If this distance is less than the
previously recorded distance (infinity in the beginning, zero for the initial node), overwrite the
distance.
6. When we are done considering all neighbors of the current node, mark it as visited. A visited
node will not be checked ever again; its distance recorded now is final and minimal.
7. Set the unvisited node with the smallest distance (from the initial node) as the next "current
node" and continue from step 3 .
PROGRAM:
#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;
RESULT:
Thus the C program to implement Dijikstra‟s algorithm was written and executed
successfully.
Ex. No: 10 IMPLEMENTATION OF PRIM’S ALGORITHM
AIM:
To write a C program to implement Prim‟s Algorithm
ALGORITHM:
1) Create a set Sthat keeps track of vertices already included in MST.
2) Assign a key value to all vertices in the input graph. Initialize all key values as INFINITE.
Assign key value as 0 for the first vertex so that it is picked first.
3) While S doesn‟t include all vertices.
a) Pick a vertex u which is not there in Sand has minimum key value.
b) Include u to S.
c) Update key value of all adjacent vertices of u.
4)To update the key values, iterate through all adjacent vertices. For every adjacent vertex v, if
weight of edge u-v is less than the previous key value of v, update the key value as weight of u-v
5)The idea of using key values is to pick the minimum weight edge from cut. The key values are
used only for vertices which are not yet included in MST, the key value for these vertices
indicate the minimum weight edges connecting them to the set of vertices included in MST.
PROGRAM:
#include<stdio.h>
int a,b,u,v,n,i,j,ne=1;
int visited[10]={0},min,mincost=0,cost[10][10];
void main()
{
printf("\n Enter the number of nodes:");
scanf("%d",&n);
printf("\n Enter 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,b,min);
mincost+=min;
visited[b]=1;
}
cost[a][b]=cost[b][a]=999;
}
printf("\n Minimun cost=%d",mincost);
}
OUTPUT:
RESULT:
Thus the C program is written for Prims algorithm and is executed successfully.
Ex.no:11a LINEAR SEARCH
AIM:
To implement the Linear search algorithm using C.
ALGORITHM:
1: Read the search element from the user
2: Compare, the search element with the first element in the list.
3: If both are matching, then display "Given element found!!!" and terminate the function
4: If both are not matching, then compare search element with the next element in the list
sequentially.
5: Repeat steps 3 and 4 until the search element is compared with the last element in the list.
6: If the last element in the list is also doesn't match, then display "Element not found!!!" and
terminate the function.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void main() {
int a[10],i,n,m,c=0;
printf("Enter the size of an array: ");
scanf("%d",&n);
printf("Enter the elements of the array: ");
for(i=0;i<=n-1;i++)
scanf("%d",&a[i]);
printf("Enter the number to be searched: ");
scanf("%d",&m);
for(i=0;i<=n-1;i++)
{
if(a[i]==m)
{
printf("Element is in the position %d\n",i+1);
c=1;
break;
}
}
if(c==0)
printf("The number is not in the list");
getch();
}
OUTPUT:
Enter the size of an array: 4
Enter the elements of the array: 4 3 5 1
Enter the number to be search: 5
Element is in the position 3
RESULT:
Thus, the program to implement the Linear Search algorithm in C was executed
successfully.
Ex.no:11b BINARY SEARCH
AIM:
To implement the binary search algorithm using C.
ALGORITHM:
1. First check the search element at the middle of the list
2. If the middle element is the search key, then the data found. Stop the searching.
3. If the key to be searched is smaller than the middle element then continue with the bottom half
of the list.
4. If the key to be searched is greater than the middle element then continue with the top half of
the list
5. Repeat the above steps till the sub array not possible further divide.
PROGRAM
#include<stdio.h>
#include <conio.h>
void main()
{
int A[10], i, n, key,c=0;
int mid, low, high;
printf(“Enter the size of an array:”);
scanf(“%d”, &n);
printf(“Enter the elements in ascending order :”);
for( i = 1; i <= n; i++)
scanf(“%d”, &A[i]);
low = 1;
high = n;
printf(“Enter the number to be searched:”);
scanf(“%d”, &key);
while ( low <= high)
{
mid = (low + high) / 2;
if ( A[mid] == key)
c=1;
break;
else if ( A[mid] < Key )
low = mid+ 1;
else
high = mid – 1;
}
if(c==0)
printf("The number is not found.");
else
printf("The number is found.");
getch();
}
OUTPUT:
Enter the size of an array: 5
Enter the elements in ascending order: 4 7 8 11 21
Enter the number to be searched: 11
The number is found
RESULT:
Thus, the program to implement the Linear Search algorithm in C was executed successfully
Ex.no:12 a INSTERTION SORT
AIM:
To write a C program to implement the concept of Insertion sort
ALGORITHM:
1: Get the elements to be sorted as input.
2: Divide the list recursively into two halves until it can no more be divided.
3: Merge the smaller lists into new list in sorted order.
4: Display the sorted list.
PROGRAM:
#include<stdio.h>
int main(){
/* Here i & j for loop counters, temp for swapping,
* count for total number of elements, number[] to
* store the input numbers in array. You can increase
* or decrease the size of number array as per requirement
*/
int i, j, count, temp, number[25];
OUTPUT
RESULT:
Thus a C program for the concept of insertion sort was implemented successfully
Ex.no:12 b SELECTION SORT
Aim :
To arrange the numbers in ascending order using selection sort.
ALGORITHM:
1: Set max_pos to location 0
2: Search the maximum element in the list
3: Swap with value at location max_pos
4: Increment max_pos to point to the next element
5: Repeat until list is sorted
PROGRAM:
#include,stdio.h>
#include,conio.h>
void main()
{
int i, j, temp, n, a[10];
printf("Enter the value of N \n");
scanf("%d", &n);
printf("Enter the numbers \n");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);
for (i = 0; i < n; i++)
{
for (j = i + 1; j < n; j++)
{
if (a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("The numbers arranged in ascending order are given below \n");
for (i = 0; i < n; i++)
printf("%d\n", a[i]);
printf("The numbers arranged in descending order are given below \n");
for(i=n-1;i>=0;i--)
printf("%d\n",a[i]);
getch();
}
OUTPUT:
Enter the value of N 4
Enter the numbers 10 2 5 3
The numbers arranged in ascending order are given below
2 3 5 10
The numbers arranged in descending order are given below
10 5 3 2
RESULT:
Thus a C program for the concept of selection sort was implemented successfully
Ex.no:13 MERGE SORT
AIM:
To implement the Merge sort algorithm using C.
ALGORITHM:
1: Get the elements to be sorted as input.
2: Divide the list recursively into two halves until it can no more be divided.
3: Merge the smaller lists into new list in sorted order.
4: Display the sorted list.
PROGRAM:
#include<stdio.h>
#include<conio.h>
void mergesort(int a[],int i,int j);
void merge(int a[],int i1,int j1,int i2,int j2);
int main()
{
int a[30],n,i;
printf("Enter no of elements:");
scanf("%d",&n);
printf("Enter array elements:");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\nSorted array is :");
for(i=0;i<n;i++)
printf("%d ",a[i]);
getch();
return 0;
}
void mergesort(int a[],int i,int j)
{
int mid;
if(i<j)
{
mid=(i+j)/2;
mergesort(a,i,mid); //left recursion
mergesort(a,mid+1,j); //right recursion
merge(a,i,mid,mid+1,j); //merging of two sorted sub-arrays
}
}
void merge(int a[],int i1,int j1,int i2,int j2)
{
int temp[50]; //array used for merging
int i,j,k;
i=i1; //beginning of the first list
j=i2; //beginning of the second list
k=0;
RESULT:
Thus, the program to implement the Merge Sort algorithm in C was executed
successfully.
Ex.no:14a OPEN ADDRESSING (LINEAR PROBING)
AIM:
To write a C program to implement linear probing to avoid collision.
ALGORITHM:
1. Calculate the hash key using key = data % size;
2. If hashTable[key] is empty, store the value directly using hashTable[key] = data.
3.If the hash index already has some value, check for next index using
key = (key+1) % size;
4.If the next index is available hashTable[key], store the value. Otherwise try for next index.
5.Repeat the steps1 to 4 till we find the space.
PROGRAM:
#include <stdio.h>
#include<conio.h>
#include<stdlib.h>
#define TABLE_SIZE 10
int h[TABLE_SIZE]={NULL};
void insert()
{
int key,index,i,flag=0,hkey;
printf("Enter a value to insert into hash table: ");
scanf("%d",&key);
hkey=key%TABLE_SIZE;
for(i=0;i<TABLE_SIZE;i++)
{
index=(hkey+i)%TABLE_SIZE;
if(h[index] == NULL)
{
h[index]=key;
break;
}
}
if(i == TABLE_SIZE)
printf("\nElement cannot be inserted!\n");
}
void search()
{
int key,index,i,flag=0,hkey;
printf("Enter search element: ");
scanf("%d",&key);
hkey=key%TABLE_SIZE;
for(i=0;i<TABLE_SIZE; i++)
{
index=(hkey+i)%TABLE_SIZE;
if(h[index]==key)
{
printf("Value is found at index: %d",index);
break;
}
}
if(i == TABLE_SIZE)
printf("Value is not found!");
}
void display()
{
int i;
printf("\nElements in the hash table are:");
for(i=0;i< TABLE_SIZE; i++)
}
OUTPUT:
RESULT:
Thus the C program is written and verified for linear probing successfully.
Ex.no:14b. OPEN ADDRESSING (QUADRATIC PROBING)
AIM:
ALGORITHM:
1. Let hash(x) be the slot index computed using the hash function and m be the size of the hash
table.
2. If the slot hash(x) % m is full, then we try (hash(x) + 12) % m.
3.If (hash(x) + 12) % m is also full, then we try (hash(x) + 22) % m.
4.If (hash(x) + 22) % m is also full, then we try (hash(x) + 32) % m.
This process is repeated for all the values of i until an empty slot is found.
PROGRAM:
#include <stdio.h>
#include<stdlib.h>
#define TABLE_SIZE 10
int h[TABLE_SIZE]={NULL};
void insert()
{
int key,index,i,flag=0,hkey;
printf("\nenter a value to insert into hash table\n");
scanf("%d",&key);
hkey=key%TABLE_SIZE;
for(i=0;i<TABLE_SIZE;i++)
{
index=(hkey+i*i)%TABLE_SIZE;
if(h[index] == NULL)
{
h[index]=key;
break;
}
}
if(i == TABLE_SIZE)
printf("\nelement cannot be inserted\n");
}
void search()
{
int key,index,i,flag=0,hkey;
printf("\nenter search element\n");
scanf("%d",&key);
hkey=key%TABLE_SIZE;
for(i=0;i<TABLE_SIZE; i++)
{
index=(hkey+i*i)%TABLE_SIZE;
if(h[index]==key)
{
printf("value is found at index %d",index);
break;
}
}
if(i == TABLE_SIZE)
printf("\n value is not found\n");
}
void display()
{
int i;
printf("\nelements in the hash table are \n");
for(i=0;i< TABLE_SIZE; i++)
printf("\nat index %d \t value = %d",i,h[i]);
}
main()
{
int opt,i;
while(1)
{
printf("\nPress 1. Insert\t 2. Display \t3. Search \t4.Exit \n");
scanf("%d",&opt);
switch(opt)
{
case 1:
insert();
break;
case 2:
display();
break;
case 3:
search();
break;
case 4:exit(0);
}
}
}
OUTPUT:
RESULT:
Thus the C program is written and verified for linear probing successfully.