Data Structure Lab Manual
Data Structure Lab Manual
LAB MANUAL
www.jntufastupdates.com
COMPUTER SCIENCE AND ENGINEERING
Program Outcomes
PO1 Engineering knowledge: Apply the knowledge of mathematics, science, engineering fundamentals,
and an engineering specialization to the solution of complex engineering problems.
PO2 Problem analysis: Identify, formulate, review research literature, and analyze complex engineering
problems reaching substantiated conclusions using first principles of mathematics, natural sciences,
and engineering sciences.
PO3 Design/development of solutions: Design solutions for complex engineering problems and design
system components or processes that meet the specified needs with appropriate consideration for the
public health and safety, and the cultural, societal, and environmental considerations.
PO4 Conduct investigations of complex problems: Use research-based knowledge and research methods
including design of experiments, analysis and interpretation of data, and synthesis of the information
to provide valid conclusions.
PO5 Modern tool usage: Create, select, and apply appropriate techniques, resources, and modern
engineering and IT tools including prediction and modeling to complex engineering activities with an
understanding of the limitations.
PO6 The engineer and society: Apply reasoning informed by the contextual knowledge to assess societal,
health, safety, legal and cultural issues and the consequent responsibilities relevant to the
professional engineering practice.
PO7 Environment and sustainability: Understand the impact of the professional engineering solutions in
societal and environmental contexts, and demonstrate the knowledge of, and need for sustainable
development.
PO8 Ethics: Apply ethical principles and commit to professional ethics and responsibilities and norms of the
engineering practice.
PO9 Individual and team work: Function effectively as an individual, and as a member or leader in diverse
teams, and in multidisciplinary settings.
PO10 Communication: Communicate effectively on complex engineering activities with the engineering
community and with society at large, such as, being able to comprehend and write effective reports
and design documentation, make effective presentations, and give and receive clear instructions.
PO11 Project management and finance: Demonstrate knowledge and understanding of the engineering and
management principles and apply these to one’s own work, as a member and leader in a team, to
manage projects and in multidisciplinary environments.
PO12 Life-long learning: Recognize the need for, and have the preparation and ability to engage in
independent and life-long learning in the broadest context of technological change.
Program Specific Outcomes
PSO1 Professional Skills: The ability to research, understand and implement computer programs in the
areas related to algorithms, system software, multimedia, web design, big data analytics, and
networking for efficient analysis and design of computer-based systems of varying complexity.
PSO2 Problem-Solving Skills: The ability to apply standard practices and strategies in software project
development using open-ended programming environments to deliver a quality product for business
success.
PSO3 Successful Career and Entrepreneurship: The ability to employ modern computer languages,
environments, and platforms in creating innovative career paths, to be an entrepreneur, and a zest for
higher studies.
www.jntufastupdates.com
DATA STRUCTURES LAB SYLLABUS
www.jntufastupdates.com
ATTAINMENT OF PROGRAM OUTCOMES
& PROGRAM SPECIFIC OUTCOMES
Program
Program
Exp. Specific
Experiment Outcomes
No. Outcomes
Attained
Attained
1 Write a C program that uses functions to perform the following:
a) Create a singly linked list of integers. PO1, PO2
PSO1
b) Delete a given integer from the above linked list.
c) Display the contents of the above list after deletion.
2 Write a C program that uses functions to perform the following:
a) Create a doubly linked list of integers.
PO1, PO2 PSO1
b) Delete a given integer from the above doubly linked list.
c) Display the contents of the above list after deletion.
3 Write a C program that uses stack operations to convert a given infix
expression into its postfix equivalent. Implement the stack using an PO1, PO2 PSO1, PSO2
array.
4 Write C programs to implement a double ended queue ADT using i)
array and ii) doubly linked list respectively. PO1, PO2 PSO1
1 *Write a C Program to check whether two given lists are containing the
same data. PO1, PO2 PSO1
www.jntufastupdates.com
Program
Program
Exp. Specific
Experiment Outcomes
No. Outcomes
Attained
Attained
4 *Write a C program to implement stack using linked list.
PO1 PSO1
www.jntufastupdates.com
DATA STRUCTURES LABORATORY
OBJECTIVE:
The objective of this lab is to teach students various data structures and to explain them algorithms
for performing various operations on these data structures. This lab complements the data
structures course. Students will gain practical knowledge by writing and executing programs in C
using various data structures such as arrays, linked lists, stacks, queues, trees, graphs, hash tables
and search trees.
OUTCOMES:
Upon the completion of Data Structures practical course, the student will be able to:
1. Design and analyze the time and space efficiency of the data structure.
4. Choose the appropriate data structure and algorithm design method for a specified
application.
www.jntufastupdates.com
EXPERIMENT 1
1.1 OBJECTIVE
1. To create a singly linked list of integers.
2. Delete a given integer from the above linked list.
3. Display the contents of the above list after deletion.
1.2 RESOURCE:
Turbo C
1.4 PROCEDURE
Go to debug -> run or press CTRL + F9 to run the program.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<math.h>
/*declaring a structure to create a node*/
struct node
{
int data;
struct node *next;
};
struct node *start;
1
www.jntufastupdates.com
void insertend(void)
{
struct node *nn,*lp;int b;
nn=(struct node *)malloc(sizeof(struct node));
printf("enter data:");
scanf("%d",&nn->data);
b=nn->data;
if(start==NULL)
{
nn->next=NULL;
start=nn;
}
else
{
lp=start;
while(lp->next!=NULL)
{
lp=lp->next;
}
lp->next=nn;
nn->next=NULL;
}
printf("%d is succ. inserted\n",b);
return;
}
/*function to insert values from the middle of the linked list*/
void insertmid(void)
{
struct node *nn,*temp,*ptemp;int x,v;
nn=(struct node *)malloc(sizeof(struct node));
if(start==NULL)
{
printf("sll is empty\n"); return;
}
printf("enter data before which no. is to be inserted:\n");
scanf("%d",&x);
if(x==start->data)
{
insertbeg();
return;
}
ptemp=start;
temp=start->next;
while(temp!=NULL&&temp->data!=x)
{
ptemp=temp;
temp=temp->next;
}
if(temp==NULL)
{
printf("%d data does not exist\n",x);
}
else
{
printf("enter data:");
scanf("%d",&nn->data);
v=nn->data;
ptemp->next=nn;
2
www.jntufastupdates.com
nn->next=temp;
printf("%d succ. inserted\n",v);
}
return;
}
/*deletion operation*/
void deletion(void)
{
struct node *pt,*t;
int x;
if(start==NULL)
{
printf("sll is empty\n");
return;
}
printf("enter data to be deleted:");
scanf("%d",&x);
if(x==start->data)
{
t=start;
/* assigning first node pointer to next nod pointer to delete a data
from the starting of the node*/
start=start->next;
free(t);
printf("%d is succ. deleted\n",x);
return;
}
pt=start;
t=start->next;
while(t!=NULL&&t->data!=x)
{
pt=t;t=t->next;
}
if(t==NULL)
{
printf("%d does not exist\n",x);return;
}
else
{
pt->next=t->next;
}
printf("%d is succ. deleted\n",x);
free(t);
return;
}
void display(void)
{
struct node *temp;
if(start==NULL)
{
printf("sll is empty\n");
return;
}
printf("elements are:\n");
temp=start;
while(temp!=NULL)
{
printf("%d\n",temp->data);
3
www.jntufastupdates.com
temp=temp->next;
}
return;
}
/* main program*/
int main()
{
int c,a; start=NULL;
do
{
printf("1:insert\n2:delete\n3:display\n4:exit\nenter choice:");
scanf("%d",&c);
switch(c)
{
case 1:
printf("1:insertbeg\n2:insert end\n3:insert mid\nenter choice:");
scanf("%d",&a);
switch(a)
{
case 1:insertbeg(); break;
case 2:insertend(); break;
case 3:insertmid(); break;
}
break;
case 2:deletion(); break;
case 3:display(); break;
case 4:printf("program ends\n");break;
default:printf("wrong choice\n");
break;
}
}while(c!=4);return 0;
}
1. Write a program to insert a node at first , last and at specified position of linked list
2. Write a program to delete a node from first, last and at specified position of linked list
4
www.jntufastupdates.com
1.9 INPUT AND OUTPUT
5
www.jntufastupdates.com
EXPERIMENT 2
2.1 OBJECTIVE
1. Create a doubly linked list of integers.
2. Delete a given integer from the above doubly linked list.
3. Display the contents of the above list after deletion.
2.2 RESOURCE
Turbo C
2.4 PROCEDURE
Go to debug -> run or press CTRL + F9 to run the program
#include<stdio.h>
#include<stdlib.h>
/*declaring a structure to create a node*/
struct node
{
struct node *prev;
int data;
struct node *next;
};
struct node *start,*nt;
/* inserting nodes into the list*/
/*function to insert values from beginning of the the double linked list*/
void insertbeg(void)
{
int a;
struct node *nn,*temp;
/*allocating implicit memory to the node*/
nn=(struct node *)malloc(sizeof(struct node));
printf("enter data:");
scanf("%d",&nn->data);
a=nn->data;
if(start==NULL) /*checking if List is empty*/
{
nn->prev=nn->next=NULL;
start=nn;
}
else
{
nn->next=start;
nn->prev=NULL;
start->prev=nn;
start=nn;
}
printf("%d succ inserted \n",a);
6
www.jntufastupdates.com
}
/*function to insert values from the end of the linked list*/
void insertend(void)
{
int b;
struct node *nn,*lp;
nn=(struct node *)malloc(sizeof(struct node));
printf("enter data:");
scanf("%d",&nn->data);
b=nn->data;
if(start==NULL)
{
/* assigning first node pointer to next nod pointer to delete a data from the starting
of the node*/
nn->prev=nn->next=NULL;
start=nn;
}
else
{
lp=start;
while(lp->next!=NULL)
{
lp=lp->next;
}
nn->prev=lp;
lp->next=nn;
nn->next=NULL;
}
printf("%d succ inserted\n",b);
}
/*function to insert values from the middle of the linked list*/
void insertmid(void)
{
struct node *nn,*temp,*ptemp;
int x,c;
if(start==NULL)
{
printf("dll is empty\n");
return;
}
printf("enter data before which nn is to be inserted\n");
scanf("%d",&x);
if(x==start->data)
{
insertbeg();
}
ptemp=start;
temp=start->next;
while(temp->next!=NULL&&temp->data!=x)
{
ptemp=temp;
temp=temp->next;
}
if(temp==NULL)
{
7
www.jntufastupdates.com
printf("%d does not exit\n",x);
}
else
{
/*allocating implicit memory to the node*/
8
www.jntufastupdates.com
free(t);
}
}
printf("%d is succ deleted\n",x);
}
}
/*end of deletion operation*/
/*display operation*/
void display()
{
struct node *temp;
if(start==NULL)
printf("stack is empty ");
temp=start;
while(temp->next!=NULL)
{
printf("%d",temp->data);
temp=temp->next;
}
printf("%d",temp->data);
}
/*end of display operation*/
/*main program*/
int main()
{
int c,a;
start=NULL;
do
{
printf("1.insert\n2.delete\n3.display\n4.exit\nenter choice:");
scanf("%d",&c);
switch(c)
{
case 1:printf("1.insertbeg\n2.insertend\n3.insertmid\nenter choice:");
scanf("%d",&a);
switch(a)
{
case 1:insertbeg();
break;
case 2:insertend();
break;
case 3:insertmid();
break;
}
break;
case 2:deletion();
break;
case 3:display();
break;
case 4:printf("program ends\n");
break;
default:printf("wrong choice\n");
break;
}
}
while(c!=4);
return 0;
}
9
www.jntufastupdates.com
2.6 PRE LAB QUESTIONS
1. What is double linked list
2. How to represent a node in double linked list
3. Differentiate between single and double linked list
10
www.jntufastupdates.com
EXPERIMENT 3
3.1 OBJECTIVE
To convert a given infix expression into its postfix Equivalent, Implement the stack using an
array.
3.2 RESOURCE:
Turbo C
3.4 PROCEDURE:
Go to debug -> run or press CTRL + F9 to run the program
Program to convert a given infix expression into its postfix Equivalent, Implement the stack
using an array.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#define MAX 20
char stack[MAX];
int top=1;
char pop(); /*declaration of pop function*/
void push(char item); /*declaration of push function*/
int prcd(char symbol) /*checking the precedence*/
{
switch(symbol) /*assigning values for symbols*/
{
case '+':
case '-': return 2;
break;
case '*':
case '/': return 4;
break;
case '^':return 6;
break;
case '(':
case ')':
case '#':return 1;
break;
}
}
int(isoperator(char symbol)) /*assigning operators*/
{
switch(symbol)
{
case '+':
case '*':
11
www.jntufastupdates.com
case '-':
case '/':
case '^':
case '(':
case ')':return 1;
break;
default:return 0;
}
}
/*converting infix to postfix*/
void convertip(char infix[],char postfix[])
{
int i,symbol,j=0;
stack[++top]='#';
for(i=0;i<strlen(infix);i++)
{
symbol=infix[i];
if(isoperator(symbol)==0)
{
postfix[j]=symbol;
j++;
}
else
{
if(symbol=='(')
push(symbol); /*function call for pushing elements into the stack*/
else if(symbol==')')
{
while(stack[top]!='(')
{
postfix[j]=pop();
j++;
}
pop(); /*function call for popping elements into the stack*/
}
else
{
if(prcd(symbol)>prcd(stack[top]))
push(symbol);
else
{
while(prcd(symbol)<=prcd(stack[top]))
{
postfix[j]=pop();
j++;
}
push(symbol);
}/*end of else loop*/
}/*end of else loop*/
} /*end of else loop*/
}/*end of for loop*/
While (stack[top]!='#')
{
postfix[j]=pop();
j++;
}
postfix[j]='\0'; /*null terminate string*/
}
12
www.jntufastupdates.com
/*main program*/
void main()
{
char infix[20],postfix[20];
printf("enter the valid infix string \n");
gets(infix);
convertip(infix,postfix); /*function call for converting infix to postfix */
printf("the corresponding postfix string is:\n");
puts(postfix);
}
/*push operation*/
void push(char item)
{
top++;
stack[top]=item;
}
/*pop operation*/
char pop()
{
char a;
a=stack[top];
top--;
return a;
}
13
www.jntufastupdates.com
EXPERIMENT 4
4.1 OBJECTIVE
1. To implement a double ended queue ADT using arrays.
2. To implement a double ended queue ADT using doubly linked list.
4.2 RESOURCE:
Turbo C
4.4 PROCEDURE:
Go to debug -> run or press CTRL + F9 to run the program
#include<stdio.h>
#define SIZE 30
int dequeue[SIZE];
int front=-1,rear=-1; /* initializing front and rear*/
void insertrear(int);
void deletefront();
void insertfront(int);
void deleterear();
void traverse();
/*main program*/
void main()
{
int choice,item;
char ch;
do
{
printf("\n options are");
printf("\n press 1 to insert at rear");
printf("\n press 2 to delete at front");
printf("\n press 3 to insert at front");
printf("\n press 4 to delete at rear");
scanf("%d",&choice);
switch(choice) /*switch case*/
{
case 1: printf("\n enter the element:");
scanf("%d",&item);
insertrear(item); /*function call for inserting element at rear*/
break;
case 2: deletefront(); /*function call for deleting element at front*/
14
www.jntufastupdates.com
break;
case 3: printf("enter the element:");
scanf("%d",&item);
insertfront(item); /*function call for inserting element at front*/
break;
case 4: deleterear();/*function call for deleting element at rear*/
break;
case 5: traverse(); /*traversing the list*/
break;
default : printf("wrong choice");
} /*end of switch case*/
printf("\n do you want to perform more operations?(Y/N):");
fflush(stdin);
scanf(" %c",&ch);
} while(ch=='Y'||ch=='y');
}
/*insertion at rear*/
void insertrear(int value) /*function definition*/
{
if(rear==(SIZE-1))
{
printf("overflow");
return;
}
else
{
if(front==-1)
{
printf("underflow so front will be modified");
front=front+1;
}
rear=rear+1;
dequeue[rear]=value;
}
}
/*deletion at front*/
void deletefront() /*function definition*/
{
int value;
if(front==-1)
{
printf("queue is already empty");
value=-1;
}
else
{
value=dequeue[front];
if(front==rear)
{
printf("queue contains only one item");
rear=-1;
front=-1;
}
else
front=front+1;
}
15
www.jntufastupdates.com
printf("removed element from front is %d",value);
}
/*insertion at front*/
void insertfront(int value) /*function definition*/
{
if(front==0)
{
printf("front is at the beginning");
printf("here insertion is not possible");
return;
}
else
{
if(front==-1)
{
printf("queue is empty so both pointers will modified");
front=front+1;
rear=rear+1;
}
else
{
front=front-1;
}
dequeue[front]=value;
}
}
/*deletion at rear*/
void deleterear() /*function definition*/
{
int value;
if(front==-1)
{
printf("queue is already empty");
return;
}
else
{
value=dequeue[rear];
if(rear==front)
{
printf("queue contains only one item");
printf("rear and front will be modified");
rear=-1;
front=-1;
}
else
{
rear=rear-1;
}
}
printf("\n the removed element from rear is:%d",value);
}
/*traverse operation*/
void traverse() /*function definition*/
{
int i;
16
www.jntufastupdates.com
if(front==-1)
{
printf("queue empty");
return;
}
else
{
printf("\n value in the queue are as follow:");
for(i=front;i<=rear;i++)
printf("\n%d",dequeue[i]);
}
}
program to implement double ended queue adt using doubly linked list
#include <stdio.h>
#include <stdlib.h>
/*declaring a structure to create a node*/
struct node
{
int data;
struct node *prev, *next;
};
/* create sentinel(dummy head & tail) that helps us to do insertion and deletion
operation at front and rear so easily. And these dummy head and tail wont get deleted
till the end of execution of this program */
17
www.jntufastupdates.com
}
void dequeueAtRear()
{
struct node *temp;
if (tail->prev == head)
{
printf("Queue is empty\n");
}
Else
{
temp = tail->prev;
tail->prev = temp->prev;
temp->prev->next = tail;
free(temp);
}
return;
}
18
www.jntufastupdates.com
printf("Queue is empty\n");
return;
}
temp = head->next;
while (temp != tail)
{
printf("%-3d", temp->data);
temp = temp->next;
}
printf("\n");
}
/*main program*/
int main()
{
int data, ch;
createSentinels();
while (1)
{
printf("1. Enqueue at front\n2. Enqueue at rear\n");
printf("3. Dequeue at front\n4. Dequeue at rear\n");
printf("5. Display\n6. Exit\n");
printf("Enter your choice:");
scanf("%d", &ch);
switch (ch) /*switch case*/
{
case 1:
printf("Enter the data to insert:");
scanf("%d", &data);
enqueueAtFront(data);
break;
case 2:
printf("Enter ur data to insert:");
scanf("%d", &data);
enqueueAtRear(data);
break;
case 3:
dequeueAtFront();
break;
case 4:
dequeueAtRear();
break;
case 5:
display();
break;
case 6:
exit(0);
default:
printf("Pls. enter correct option\n");
break;
} /*end of switch case*/
19
www.jntufastupdates.com
}
return 0;
}
20
www.jntufastupdates.com
double ended queue adt using doubly linked list
21
www.jntufastupdates.com
22
www.jntufastupdates.com
EXPERIMENT 5
5.1 OBJECTIVE
1. To create a binary search tree of characters.
2. Traverse the above Binary search tree recursively in Post order.
5.2 RESOURCE:
Turbo C
5.4 PROCEDURE:
Go to debug -> run or press CTRL + F9 to run the program
#include<stdio.h>
#include<stdlib.h>
typedef struct BST
{
char d;
/*declaring a structure to create a node*/
23
www.jntufastupdates.com
nn->rc=NULL;
scanf(" %c",&nn->d);
if(root==NULL)
root=nn;
else
insert(root,nn);
printf("\n want to enter more elements?(Y/N)");
scanf(" %c",&ans);
}while(ans=='y');
break;
case 2:
if(root==NULL)
printf("tree is not created");
else
{
printf("\n the inorder display:");
inorder(root);
printf("\n the preorder display:");
preorder(root);
printf("\n the postorder display:");
postorder(root);
}
break;
} /*end of switch case*/
}while(choice!=3);
}
/*insertion operation*/
void insert(node *root,node *nn)
{
int c,d;
c=nn->d;
d=root->d;
if(c<d)
{
if(root->lc==NULL)
root->lc=nn;
else
insert(root->lc,nn);
}
}
/*inorder traversal*/
void inorder(node *temp)
{
if(temp!=NULL)
{
inorder(temp->lc);
printf(" %c",temp->d);
inorder(temp->rc);
}
}
/*preorder traversal*/
void preorder(node *temp)
{
if(temp!=NULL)
{
printf(" %c",temp->d);
preorder(temp->lc);
preorder(temp->rc);
24
www.jntufastupdates.com
}
}
/*postorder traversal*/
void postorder(node *temp)
{
if(temp!=NULL)
{
postorder(temp->lc);
postorder(temp->rc);
printf(" %c",temp->d);
}
}
1. Construct a binary search tree for the following 80, 40, 75, 30, 20, 90, 50
25
www.jntufastupdates.com
EXPERIMENT 6
6.1 OBJECTIVE
1. Create a binary search tree of integers.
2. Traverse the above Binary search tree non recursively in inorder.
6.2 RESOURCE:
Turbo C
6.4 PROCEDURE
Go to debug -> run or press CTRL + F9 to run the program
#include<stdio.h>
#include<conio.h>
typedef struct bint
{
/*declaring a structure to create a node*/
int data,flag;
struct bint *left,*right;
}node;
node * create(node *r,int d)
{
if(r == NULL)
{
/*allocating implicit memory to the node*/
r = (node *)malloc(sizeof(node));
r->data = d;
r->left = r->right = NULL;
}
else
{
if(r->data <= d)
r->right = create(r->right,d);
else
r->left = create(r->left,d);
}
return r;
}
void non_in(node *r)
{
int top=0;
node *s[20],*pt=r;
s[0]=NULL;
26
www.jntufastupdates.com
while(pt != NULL)
{
s[++top] = pt;
pt = pt->left;
}
pt = s[top--];
while(pt != NULL)
{
printf("%d\t",pt->data);
if(pt->right != NULL)
{
pt = pt->right;
while(pt != NULL)
{
s[++top] = pt;
pt = pt->left;
}
}
pt = s[top--];
}
}
/*main program*/
void main()
{
int d;
char ch = 'Y';
node *root = NULL;
clrscr();
while(toupper(ch) == 'Y')
{
printf("\n Enter the item to insert");
scanf("%d",&d);
head = create(root,d);
printf("\n Do you want to continue(y/n)");
fflush(stdin);
ch = getchar();
}
1 Construct a binary search tree for the following 80, 40, 75, 30, 20, 90, 50
27
www.jntufastupdates.com
6.9 INPUT AND OUTPUT
28
www.jntufastupdates.com
EXPERIMENT 7
7.1 OBJECTIVE
1. Arrange a list of integers in ascending order using Insertion sort
2. Arrange a list of integers in ascending order using Merge sort
7.2 RESOURCE
Turbo C
INSERTION SORT
1. Start with an empty left hand [sorted array] and the cards face down on the table [unsorted array].
2. Then remove one card [key] at a time from the table [unsorted array], and insert it into the correct
position in the left hand [sorted array].
3. To find the correct position for the card, we compare it with each of the cards already in the hand,
from right to left.
MERGE SORT
1. Divide Step
If a given array A has zero or one element, simply return; it is already sorted. Otherwise,
split A[p .. r] into two subarrays A[p .. q] and A[q + 1 .. r], each containing about half of the
elements of A[p .. r]. That is, q is the halfway point of A[p .. r].
2. Conquer Step
Conquer by recursively sorting the two subarrays A[p .. q] and A[q + 1 .. r].
3. Combine Step
Combine the elements back in A[p .. r] by merging the two sorted subarrays A[p .. q] and A[q + 1
.. r] into a sorted sequence. To accomplish this step, we will define a procedure MERGE
(A, p, q, r).
7.4 PROCEDURE:
Go to debug -> run or press CTRL + F9 to run the program
Insertion sort
#include<stdio.h>
void inst_sort(int[]);
void main() {
int num[5],count;
printf("\n enter the five elements to sort:\n");
for(count=0;count<5;count++)
scanf("%d",&num[count]);
inst_sort(num); /*function call for insertion sort*/
printf("\n\n elements after sorting:\n");
for(count=0;count<5;count++)
printf("%d\n",num[count]);
}
void inst_sort(int num[]) { /* function definition for insertion sort*/
int i,j,k;
for(j=1;j<5;j++) {
k=num[j];
for(i=j-1;i>=0&&k<num[i];i--)
29
www.jntufastupdates.com
num[i+1]=num[i];
num[i+1]=k;
}}
Merge sort
#include<stdio.h>
void mergesort(int[],int,int);
void mergearray(int[],int,int,int);
main() {
int a[50],n,i;
printf("\n enter size of an array:");
scanf("%d",&n);
printf("\n enter elements of an array:\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
mergesort(a,0,n-1);
printf("\n\nafter sorting:\n");
for(i=0;i<n;i++)
printf("\n%d",a[i]);
}
/*merge operation*/
void mergesort(int a[],int beg,int end) {
int mid;
if(beg<end) {
mid=(beg+end)/2;
mergesort(a,beg,mid);
mergesort(a,mid+1,end);
mergearray(a,beg,mid,end);
} }
void mergearray(int a[],int beg,int mid,int end) {
int i,leftend,num,temp,j,k,b[50];
for(i=beg;i<=end;i++)
b[i]=a[i];
i=beg;
j=mid+1;
k=beg;
while((i<=mid)&&(j<=end)) {
if(b[i]<+b[j])
{
a[k]=b[i];
i++;
k++;
}
else {
a[k]=b[j];
j++;
k++;
}}
if(i<=mid) {
while(i<=mid) {
a[k]=b[i];
i++;
k++;
}}
else {
while(j<=end) {
30
www.jntufastupdates.com
a[k]=b[j];
j++;
k++;
} }}
Insertion sort
Merge sort
31
www.jntufastupdates.com
EXPERIMENT 8
8.1. OBJECTIVE
1. Sorting the list of integers in ascending order using Quick sort
2. Sorting the list of integers in ascending order using Selection sort
8.2 RESOURCE:
Turbo C
8.4 PROCEDURE:
Go to debug -> run or press CTRL + F9 to run the program
QUICK SORT
#include<stdio.h>
main()
{
int x[10],i,n;
printf("enter number of elements:");
scanf("%d",&n);
printf("enter %d elements:\n");
for(i=0;i<n;i++)
scanf("%d",&x[i]);
quicksort(x,0,n-1);/*function call*/
printf("sorted elements are:");
for(i=0;i<n;i++)
printf("%3d",x[i]);
}
/*called function*/
quicksort(int x[10],int first,int last)
{
int pivot,i,j,t;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
{
while(x[i]<=x[pivot]&&i<last)
i++;
while(x[j]>x[pivot])
j--;
if(i<j)
32
www.jntufastupdates.com
{
t=x[i];
x[i]=x[j];
x[j]=t;
}
}
t=x[pivot];
x[pivot]=x[j];
x[j]=t;
quicksort(x,first,j-1);
quicksort(x,j+1,last);
}
}
SELECTION SORT
#include<stdio.h>
void sel_sort(int[]);
void main()
{
int num[5],count;
printf("enter the five elements to sort:\n");
for(count=0;count<5;count++)
scanf("%d",&num[count]);
sel_sort(num); /*function call*/
printf("\n\n elements after sorting:\n");
for(count=0;count<5;count++)
printf("%d\n",num[count]);
}
/*called function*/
void sel_sort(int num[])
{
int i,j,min,temp;
for(j=0;j<5;j++)
{
min=j;
for(i=j;i<5;i++)
if(num[min]>num[i])
min=i;
if(min<5)
{
temp=num[j];
num[j]=num[min];
num[min]=temp;
}
printf("%d\t",num[j]);
}
}
33
www.jntufastupdates.com
8.7 LAB ASSIGNMENT
1 . Rearrange the following numbers using Quick sort procedure. 42, 12, 18, 98, 67, 83,
8, 10, 71
QUICK SORT
SELECTION SORT
34
www.jntufastupdates.com
EXPERIMENT 9
9.1 OBJECTIVE
1. To perform the Insertion into a B-tree
2. Implement Heap sort algorithm
9.2 RESOURCE:
Turbo C
9.4 PROCEDURE:
Go to debug -> run or press CTRL + F9 to run the program
B-TREE
#include<stdio.h>
#include <stdlib.h>
#define M 5
struct node
{
int n; /* n < M No. of keys in node will always less than order of B
tree */
int keys[M-1]; /*array of keys*/
struct node *p[M]; /* (n+1 pointers will be in use) */
}*root=NULL;
35
www.jntufastupdates.com
switch(choice)
{
case 1:
printf("Enter the key : ");
scanf("%d",&key);
insert(key);
break;
case 3:
printf("Enter the key : ");
scanf("%d",&key);
search(key);
break;
case 4:
printf("Btree is :\n");
display(root,0);
break;
case 5:
exit(1);
default:
printf("Wrong choice\n");
break;
}/*End of switch*/
}/*End of while*/
return 0;
}/*End of main()*/
void insert(int key)
{
struct node *newnode;
int upKey;
enum KeyStatus value;
value = ins(root, key, &upKey, &newnode);
if (value == Duplicate)
printf("Key already available\n");
if (value == InsertIt)
{
struct node *uproot = root;
root=malloc(sizeof(struct node));
root->n = 1;
root->keys[0] = upKey;
root->p[0] = uproot;
root->p[1] = newnode;
}/*End of if */
}/*End of insert()*/
enum KeyStatus ins(struct node *ptr, int key, int *upKey,struct node**newnode)
{
struct node *newPtr, *lastPtr;
int pos, i, n,splitPos;
int newKey, lastKey;
enum KeyStatus value;
if (ptr == NULL)
{
*newnode = NULL;
*upKey = key;
return InsertIt;
36
www.jntufastupdates.com
}
n = ptr->n;
pos = searchPos(key, ptr->keys, n);
if (pos < n && key == ptr->keys[pos])
return Duplicate;
value = ins(ptr->p[pos], key, &newKey, &newPtr);
if (value != InsertIt)
return value;
/*If keys in node is less than M-1 where M is order of B tree*/
if (n < M - 1)
{
pos = searchPos(newKey, ptr->keys, n);
/*Shifting the key and pointer right for inserting the new key*/
for (i=n; i>pos; i--)
{
ptr->keys[i] = ptr->keys[i-1];
ptr->p[i+1] = ptr->p[i];
}
/*Key is inserted at exact location*/
ptr->keys[pos] = newKey;
ptr->p[pos+1] = newPtr;
++ptr->n; /*incrementing the number of keys in node*/
return Success;
}/*End of if */
/*If keys in nodes are maximum and position of node to be inserted is
last*/
if (pos == M - 1)
{
lastKey = newKey;
lastPtr = newPtr;
}
else /*If keys in node are maximum and position of node to be inserted
is not last*/
{
lastKey = ptr->keys[M-2];
lastPtr = ptr->p[M-1];
for (i=M-2; i>pos; i--)
{
ptr->keys[i] = ptr->keys[i-1];
ptr->p[i+1] = ptr->p[i];
}
ptr->keys[pos] = newKey;
ptr->p[pos+1] = newPtr;
}
splitPos = (M - 1)/2;
(*upKey) = ptr->keys[splitPos];
37
www.jntufastupdates.com
(*newnode)->p[(*newnode)->n] = lastPtr;
return InsertIt;
}/*End of ins()*/
HEAP SORT
#include<stdio.h>
int p(int);
int left(int);
int right(int);
void heapify(int[],int,int);
void buildheap(int[],int);
38
www.jntufastupdates.com
void heapsort(int[],int);
void main()
{
int x[20],n,i;
printf("enter the no. of elements to b sorted");
scanf("%d",&n);
printf("enter the elements ");
for(i=0;i<n;i++)
scanf("%d",&x[i]);
heapsort(x,n);
printf("sorted array is");
for(i=0;i<n;i++)
printf("%d",x[i]);
}
int p(int i)
{
return i/2;
}
int left(int i)
{
return 2*i+1;
}
int right(int i)
{
return 2*i+2;
}
void heapify(int a[],int i,int n)
{
int l,r,large,t;
l=left(i);
r=right(i);
if((l<=n-1)&&(a[l]>a[i]))
large=l;
else
large=i;
if((r<=n-1)&&(a[r]>a[large]))
large=r;
if(large!=i)
{
t=a[i];
a[i]=a[large];
a[large]=t;
heapify(a,large,n);
}
}
void buildheap(int a[],int n)
{
int i;
for(i=(n-1)/2;i>=0;i--)
heapify(a,i,n);
}
void heapsort(int a[],int n)
{
int i,m,t;
buildheap(a,n);
m=n ;
for(i=n-1;i>=1;i--)
{
39
www.jntufastupdates.com
t=a[0];
a[0]=a[i];
a[i]=t;
m=m-1;
heapify(a,0,m);
}
}
40
www.jntufastupdates.com
EXPERIMENT 10
10.1 OBJECTIVE
10.2 RESOURCE:
Turbo C
10.4 PROCEDURE:
Go to debug -> run or press CTRL + F9 to run the program
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int b;
41
www.jntufastupdates.com
empty[b]=0;
*(ht+b)=key;
printf("elements is inserted\n");
}
}
/*deletion operation*/
void delete(int key,int d,int *ht,int *empty)
{
int b=hsearch(key,d,ht,empty);
*(ht+b)=0;
empty[b]=1;
printf("element is deleted\n");
}
void display(int d,int *ht,int *empty)
{
int i;
printf("hash table elements are\n");
for(i=0;i<d;i++)
{
if(empty[i])
printf(" 0");
else
printf("%5d",*(ht+i));
}
printf("\n");
}
/*main program*/
void main()
{
int choice=1;
int key;
int d,i,s;
int *empty,*ht;
printf("enter the hash table size:");
scanf("%d",&d);
ht=(int *)malloc(d *sizeof(int));
empty=(int *)malloc(d *sizeof(int));
for(i=0;i<d;i++)
empty[i]=1;
while(1)
{
printf("\n");
printf("\n LINEAR PROBING");
printf("\n 1:insert hash table:");
printf("\n 2:delete hash table");
printf("\n 3:search hash table");
printf("\n 4:display hash table");
printf("\n 5:exit");
printf("enter your choice");
scanf("%d",&choice);
switch(choice)
{
case 1:printf("enter the elemants:");
scanf("%d",&key);
insert(key,d,ht,empty);
break;
case 2:printf("enter to remove from hash table:");
scanf("%d",&key);
42
www.jntufastupdates.com
delete(key,d,ht,empty);
break;
case 3:printf("enter the search elements:");
scanf("%d",&key);
s=search(key,d,ht,empty);
if(s==-1||s==0)
printf("not found\n");
else
printf("element found at index %d",hsearch(key,d,ht,empty));
break;
case 4:display(d,ht,empty);
break;
case 5:exit(0);
}
}return;
}
1. Use quadratic probing to fill the Hash table of size 11. Data elements are
23,0,52,61,78,33,100,8,90,10,14.
2. Analyze input (371, 323, 173, 199, 344, 679, 989) and hash function h(x)=x mod 10,
Show the result Separate Chaining, linear probing
43
www.jntufastupdates.com
10.9 INPUT AND OUTPUT
44
www.jntufastupdates.com
45
www.jntufastupdates.com
EXPERIMENT 11
11.1 OBJECTIVE
To implementing Knuth-Morris- Pratt pattern matching algorithm
11.2 RESOURCE:
Turbo C
11.4 PROCEDURE
Go to debug -> run or press CTRL + F9 to run the program
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
computefailure(pat, M, f);
46
www.jntufastupdates.com
}
free(f); }
void computefailure (char *pat, int M, int *f) //compute the failure function
{
int len = 0;
int i;
while(i < M)
{
if(pat[i] == pat[len])
{
len++;
f[i] = len;
i++;
}
else // (pat[i] != pat[len])
{
if( len != 0 )
{
len = f[len-1];
}
else // if (len == 0)
{
f[i] = 0;
i++;
}
}
}
}
int main()
{
int match;
printf("\nEnter the Text: ");
gets(text); //reading the text
printf("\nEnter the Pattern: ");
gets(pattern); //reading the pattern
m=strlen(text);
n=strlen(pattern);
match=KMPSearch(pat, txt);
if(match>=0)
{
printf("\nMatch found at position %d\n\n",match);
}
else
{
printf("\nNo Match found!!!\n\n");
}
return 0;
}
47
www.jntufastupdates.com
11.6 PRE LAB QUESTIONS
1. what is pattern matching
2. List the various pattern matching algorithms
3. What is failure function
48
www.jntufastupdates.com
EXPERIMENT 12
A: Write C programs for implementing the following graph traversal algorithm for Depth first
traversal
12.1 OBJECTIVE
To traverse graph
12.2 RESOURCE:
Turbo C
12.4 PROCEDURE:
Go to debug -> run or press CTRL + F9 to run the program
DFS
#include <stdio.h>
void dfs(int);
int g[10][10],visited[10],n,vertex[10];
void main()
{
int i,j;
printf("enter number of vertices:");
scanf("%d",&n);
printf("enter the val of vertex:");
for(i=0;i<n;i++)
scanf("%d",&vertex[i]);
printf("\n enter adjecency matrix of the graph:");
for(i=0;i<n;i++)
for(j=0;j<n;j++)
scanf("%d",&g[i][j]);
for(i=0;i<n;i++)
visited[i]=0;
dfs(0);
}
void dfs(int i)
{
int j;
printf("%d",vertex[i]);
visited[i]=1; for(j=0;j<n;j++)
if(!visited[j]&&g[i][j]==1)
dfs(j);
}
49
www.jntufastupdates.com
12.6 PRE LAB QUESTIONS
1. What is graph
2. List various way of representations of graph
3. How many graph traversal algorithms are there
50
www.jntufastupdates.com
CONTENT BEYOND SYLLABI
51
www.jntufastupdates.com
EXPERIMENT 1
1.1 OBJECTIVE
*Write a C Program to check whether two given lists are containing the same data.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
};
int main() {
struct node *p = NULL;
struct node *q = NULL;
int result;
return 0;
}
52
www.jntufastupdates.com
else {
return 1;
}
}
do {
printf("Enter number: ");
scanf("%d", &c);
temp = (struct node *)malloc(sizeof(struct node));
temp->num = c;
temp->next = *head;
*head = temp;
printf("Do you wish to continue [1/0]: ");
scanf("%d", &ch);
}while (ch != 0);
printf("\n");
}
INPUT/ OUTPUT
Enter data into first list
Enter number: 12
Do you wish to continue [1/0]: 1
Enter number: 3
Do you wish to continue [1/0]: 1
Enter number: 28
Do you wish to continue [1/0]: 1
Enter number: 9
Do you wish to continue [1/0]: 0
53
www.jntufastupdates.com
EXPERIMENT 2
2.1 OBJECTIVE
*Write a C program to find the largest element in a given doubly linked list.
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
struct node *prev;
};
int main()
{
struct node *p = NULL;
int n;
return 0;
}
q = max = head;
while (q != NULL)
{
if (q->num > max->num)
{
max = q;
}
q = q->next;
}
return (max->num);
}
54
www.jntufastupdates.com
do
{
printf("Enter number: ");
scanf("%d", &c);
temp = (struct node *)malloc(sizeof(struct node));
temp->num = c;
temp->next = NULL;
temp->prev = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
rear->next = temp;
temp->prev = rear;
}
rear = temp;
printf("Do you wish to continue [1/0]: ");
scanf("%d", &ch);
} while (ch != 0);
printf("\n");
}
INPUT/ OUTPUT:
Enter data into the list
Enter number: 12
Do you wish to continue [1/0]: 1
Enter number: 7
Do you wish to continue [1/0]: 1
Enter number: 23
Do you wish to continue [1/0]: 1
Enter number: 4
Do you wish to continue [1/0]: 1
Enter number: 1
Do you wish to continue [1/0]: 1
Enter number: 16
Do you wish to continue [1/0]: 0
55
www.jntufastupdates.com
EXPERIMENT 3
3.1 OBJECTIVE
#include <stdio.h>
#include <stdlib.h>
struct node
{
int a;
struct node *next;
};
int main()
{
struct node *head = NULL;
generate(&head);
printf("\nThe sequence of contents in stack\n");
display(head);
printf("\nInversing the contents of the stack\n");
if (head != NULL)
{
stack_reverse(&head, &(head->next));
}
printf("\nThe contents in stack after reversal\n");
display(head);
delete(&head);
return 0;
}
if (*head_next != NULL)
{
temp = (*head_next)->next;
(*head_next)->next = (*head);
*head = *head_next;
*head_next = temp;
stack_reverse(head, head_next);
}
}
56
www.jntufastupdates.com
if (head != NULL)
{
printf("%d ", head->a);
display(head->next);
}
}
INPUT/OUTPUT:
57
www.jntufastupdates.com
EXPERIMENT 4
4.1 OBJECTIVE
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;
void 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)
{
printf("\n Enter choice : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
printf("Enter data : ");
scanf("%d", &no);
push(no);
break;
case 2:
pop();
break;
58
www.jntufastupdates.com
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;
}
}
}
59
www.jntufastupdates.com
count++;
}
if (top1 == NULL)
{
printf("Stack is empty");
return;
}
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--;
}
60
www.jntufastupdates.com
while (top1 != NULL)
{
top1 = top->ptr;
free(top);
top = top1;
top1 = top1->ptr;
}
free(top1);
top = NULL;
INPUT/OUTPUT:
1 - Push
2 - Pop
3 - Top
4 - Empty
5 - Exit
6 - Dipslay
7 - Stack Count
8 - Destroy stack
Enter choice : 1
Enter data : 56
Enter choice : 1
Enter data : 80
Enter choice : 2
Popped value : 80
Enter choice : 3
Top element : 56
Enter choice : 1
Enter data : 78
Enter choice : 1
Enter data : 90
Enter choice : 6
90 78 56
Enter choice : 7
Stack is empty
Enter choice : 5
61
www.jntufastupdates.com
EXPERIMENT 5
5.1 OBJECTIVE
*Write a C program to count the number of nodes in the binary search tree.
struct node
{
int data;
struct node *lchild;
struct node *rchild;
};
void main()
{
struct node *root;
int leaf,nonleaf;
clrscr();
printf("\nCreate a binary tree \n");
root = create_bin_rec();
printf("\n Binary tree is ");
print_bin_pre_rec(root);
leaf = nonleaf = 0;
cnt_nodes(root,&leaf,&nonleaf);
printf("\n Total no. of leaf nodes are : %d ",leaf);
printf("\n Total no. of nonleaf nodes are : %d ",nonleaf);
printf("\n Total no. of nodes are : %d ", (leaf+nonleaf));
} // main
62
www.jntufastupdates.com
} // create
INPUT OUTPUT
Binary tree is 10 20
Total no. of leaf nodes are 1
Total no. of non leaf nodes are 1
Total no. of nodes are 2
63
www.jntufastupdates.com
EXPERIMENT 6
6.1 OBJECTIVE
*Write a C program to sort an array of integers in ascending order using radix sort.
#include <stdio.h>
int min = 0, count = 0, array[100] = {0}, array1[100] = {0};
void main()
{
int k, i, j, temp, t, n;
}
for (j = 0; j < count; j++) /*to find MSB */
array[j] = array[j] / 10;
}
printf("Sorted Array (lSdradix sort) : ");
for (i = 0; i < count; i++)
printf("%d ", array1[i]);
}
INPUT/ OUTPUT:
/* Average Case */
Enter size of array :7
64
www.jntufastupdates.com
Enter elements into array :170
45
90
75
802
24
2
Sorted Array (ladradix sort) : 2 24 45 75 90 170 802
/*Best case */
Enter size of array :7
Enter elements into array :22
64
121
78
159
206
348
Sorted Array (ladradix sort) : 22 64 78 159 121 206 348
/* Worst case */
Enter size of array :7
Enter elements into array :985
27
64
129
345
325
091
Sorted Array (ladradix sort) : 27 64 91 129 325 345 985
65
www.jntufastupdates.com
EXPERIMENT 7
7.1 OBJECTIVE
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main() {
char *str[5], *temp;
int i, j, n;
printf("\nHow many names do you want to have?");
scanf("%d", &n);
for (i = 0; i < n; i++) {
printf("\nEnter the name %d: ", i);
flushall();
gets(str[i]);
}
for (i = 0; i < n; i++) {
for (j = 0; j < n - 1; j++) {
if (strcmp(str[j], str[j + 1]) > 0) {
strcpy(temp, str[j]);
strcpy(str[j], str[j + 1]);
strcpy(str[j + 1], temp);
} } }
printf("\nSorted List : ");
for (i = 0; i < n; i++)
puts(str[i]);
return (0);
}
INPUT /OUTPUT:
Enter any strings :
pri
pra
pru
pry
prn
66
www.jntufastupdates.com