Dsa Lab Manual
Dsa Lab Manual
LAB MANUAL
SEMESTER 3rd
RUNGTA COLLEGE
Rungta Educational Campus,
Kohka-Kurud Road, Bhilai,
Chhattisgarh, India
Phone No. 0788-6666666
MANAGED BY : SANTOSH RUNGTA GROUP OF INSTITUTIONS
LAB MANUAL
DOs:
lab.
▪ Take help from the Manual / Work Book for preparation of the experiment.
▪ For any abnormal working of the machine consult the Faculty In-charge/
Lab Assistant.
▪ Shut down the machine and switch off the power supply after performing
the experiment.
DON’Ts:
▪ Do not tamper with the instruments in the Lab and do not disturb their
settings.
LIST OF EXPERIMENTS
AS PER THE SYLLABUS PRESCRIBED BY THE UNIVERSITY
Chhattisgarh Swami Vivekananda Technical University, Bhilai
Branch: Computer Science and Engineering Semester: III
Subject: Data Structures Laboratory Subject Code: B022321(022)
Total Lab Periods: 36 Batch Size: 30
Maximum Marks: 40 Minimum Marks: 20
COURSE OBJECTIVES
1. To implement linear and non-linear data structures
2. To Introduce basic operations on linear and non-Linear data structures
3. To understand the different operations of search trees
4. To implement graph traversal algorithms
5. To get familiarized with sorting and searching algorithms
COURSE OUTCOMES
After successful completion of this course, the students will be able to-
1. Identify the appropriate data structure for a given problem.
2. Design various data structure algorithms and estimate their time and space complexity.
3. Apply appropriate algorithms for better utilization of memory.
4. Apply practical knowledge on the applications of data structures.
5. Solve real-world problems using sorting and searching techniques.
List of Experiments
1. Write a program to perform the following operations in the one-dimensional array:
insertion, deletion, and searching (Linear and Binary).
2. Write a program to implement stack and perform push and pop operations.
4. Write a program to perform the following operations on linear queue- addition, deletion,
traversing.
5. Write a program to perform the following operations in the circular queue- addition,
deletion, and traversing.
8. Write a program to perform the following operations on a double link list – creation,
insertion, and deletion.
9. Write a program to implement polynomials in the link list and perform. a) Polynomial
arithmetic b) Evaluation of polynomial
10. Write a program to implement a linked stack and linked queue.
15. Write a program to create a Binary search tree and perform –insertion, deletion &
traversal.
TEXTBOOKS
REFERENCE BOOKS
LIST OF EXPERIMENTS
Example
Data: 345 358 490 501 513 555 561 701 724 797
Location: 0 1 2 3 4 5 6 7 8 9
Location: 0 1 2 3 4 5 6 7 8 9 10
3. Insert 505
Data: 345 358 490 501 505 513 555 561 701 724 797
Location: 0 1 2 3 4 5 6 7 8 9
1
Algorithm
Suppose, the array to be arr[max], pos to be the position at which the element
num has to be inserted. For insertion, all the elements starting from the
position pos are shifted towards their right to make a vacant space where the
element num is inserted.
//Traversal
for(int i=0;i<n;i++){
printf("%d ",arr[i]);
printf("\n");
if(size>=capacity){
return -1;
for(int i=size-1;i>=index;i--){
arr[i+1]=arr[i];
2
arr[index]=element;
return 1;
int main(){
int arr[100]={1,2,6,7,9};
int size=5,element=10,index=2;
display(arr,size);
indInsertion(arr,size,100,element,index);
size=size+1;
display(arr,size);
return 0;
Outputs :
[Running] cd "d:\DSA LAB\" && gcc tempCodeRunnerFile.c -o
tempCodeRunnerFile && "d:\DSA LAB\"tempCodeRunnerFile
1 2 6 7 9
1 2 10 6 7 9
3
Assignments:
Viva Questions:
1. What is an array?
2. Give the limitations of array.
3. Differentiate between 1-dimentional and 2-dimensional array.
4. Differentiate between static and dynamic memory allocation.
5. Is array a static or a dynamic memory system?
6. Give procedure to traverse a linear array.
7. What is ADT?
8. What is overflow?
9. What is underflow?
10. Write procedure to insert element at the beginning of the list.
Example:
Data: 345 358 490 501 513 555 561 701 724 797
Location: 0 1 2 3 4 5 6 7 8 9
1. Locate 358: If we use ‘linear search’, we’ll compare 358 with each
4
2. Delete 358: Remove it from the list (space=10).
Data: 345 490 501 513 555 561 701 724 797
Location: 0 1 2 3 4 5 6 7 8 9
Data: 345 490 501 513 555 561 701 724 797? (797)
Location: 0 1 2 3 4 5 6 7 8 9
Source code:
#include<stdio.h>
//Traversal
for(int i=0;i<n;i++){
printf("%d ",arr[i]);
printf("\n");
for(int i=index;i<=size-1;i++){
arr[i]=arr[i+1];
int main(){
5
int arr[100]={1,2,6,7,9};
int size=5,index=2;
display(arr,size);
indDeletion(arr,size,index);
size=size-1;
display(arr,size);
return 0;}
Outputs :
[Running] cd "d:\DSA LAB\" && gcc deletion.c -o deletion && "d:\DSA
LAB\"deletion
1 2 6 7 9
1 2 7 9
Assignments:
Viva Questions:
1. What is an array?
2. Give the limitations of array.
3. Differentiate between 1-dimentional and 2-dimensional array.
4. Differentiate between static and dynamic memory allocation.
5. Is array a static or a dynamic memory system?
6. Give procedure to traverse a linear array.
7. What is ADT?
8. What is overflow?
9. What is underflow?
10. Write procedure to delete last element from the list.
6
Experiment No. 2
In this algorithm in the set of ‘N’ data item is given—D1, D2 .... Dn having k1,
k2
.... kN, ‘N’ distinct respective keys. If the desired record is located that contains
the
key ‘ki’ then the search is successful otherwise unsuccessful. We assume that N
1.
Step 1 Initialization
Set i 1.
while ( i < = N)
if (k = ki) then
Else
Set i i + 1
7
}
End of loop.
Step 3 If no match
If (k ki) then
Step 4 Finish
Exit.
Source Code:
#include<stdio.h>
for(int i=0;i<size-1;i++){
if(arr[i]==element){
return i;
return -1;
int main(){
int arr[]={1,4,3,7,9,8,10};
int element = 8;
8
int searchIndex=linearSearch(arr,size,element);
return 0;
Output:
[Running] cd "d:\DSA LAB\" && gcc tempCodeRunnerFile.c -o
tempCodeRunnerFile && "d:\DSA LAB\"tempCodeRunnerFile
Assignments:
Viva Questions:
9
2.2 Binary Search:
Theory:
The above procedure searches the desired data item having key ‘K’ from the
ordered set of data items. The set consists of ‘N’ data items having ‘N’ distinct
keys
such that,
k1 < k2 < k3 < .... < kN. This procedure searches for a given
argument K,
Step 1 Initialization.
Set l 1, u N.
while (u > = l)
Set m=1.
if (K = km) then
display (K).
Set l m + 1.
else
Set u m – 1.
10
}
End of loop.
Return.
Source Code:
#include<stdio.h>
int mid,high=size-1,low=0;
if (arr[mid] == element)
return mid;
low = mid + 1;
else
11
high = mid - 1;
return -1;
//end searching
int main(){
int arr[]={1,3,5,7,9,13,17,19};
int searchIndex=binarySearch(arr,size,element);
return 0;
Output:
[Running] cd "d:\DSA LAB\" && gcc tempCodeRunnerFile.c -o
tempCodeRunnerFile && "d:\DSA LAB\"tempCodeRunnerFile
12
Assignments:
Viva Questions:
13
EXPERIMENT No. 3
a. Push
b. Pop
Theory:
Procedure Create (S) :
The function creates the stack ‘S’. The SIZE variable denotes the maximum limit of an
array it is assumed that its size is such that it can accomodate n number of elements. The
variable ‘top’ holds the topmost index of array. Initially top stores the value –1, which
shows stack is empty.
Step 1 Initialize variable top with value as – 1.
Set top 🡨 –1.
Step 2 Return at the point of call.
Return.
Function IsEmpty (S) :
This Function checks the empty condition in a stack S. The Function returns true if it
is empty otherwise false.
Step 1 Checking, Is Empty ;
if (top = –1) then
return true
else
return false
The above function can also be written by using ternary operator as follows:
14
return false.
The above function can also be written by using ternary operator as follows:
Boolean IsFull (stack * S)
{
return ( ( S 🡪 top > = SIZE —1 ) ? TRUE : FALSE ;
}
Procedure push (S, n) :
The above procedure inserts an element stored in variable ‘n’ to the top of the stack
‘S’. Variable ‘top’ holds the index of the topmost element. Stack overflow condition can
be checked by making a call to function IsFull.
Step 1 Is overflow?
if (! IsFull (S) then R Call to IsFull
Set top 🡨 top +1
Set S [top] 🡨 n.
else
message : “STACK OVERFLOW”
Step 2 Return of the point of call .
The above function can also be written in the following way:
void push (stack *S, int n )
{
if (! IsFull (S))
{
S 🡪 item [++ S 🡪 top] = n ;
}
else
printf (‘‘\n STACK OVERFLOW’’ ) ;
}
Function Pop (S) :
This Procedure deletes an element from the stack ‘S’ variable ‘top’ holds the topmost
elements index. Stack underflow (empty) condition can be checked by making a call to
Function IsEmpty.
Step 1 1s Empty?
if (! 1sEmpty (S)) then
Set temp 🡨 S [top]
Set top 🡨 top –1
else
message : ‘STACK UNDERFLOW’
Step 2 Return at the point of call.
return(temp)
15
Source Code:
#include<stdio.h>
#include<stdlib.h>
struct stack{
int size;
int top;
int* arr;
};
if(s1->top==-1){
return 1;
else{
return 0;
if(s1->top==s1->size-1){
return 1;
else{
return 0;
// push operation
16
void push(struct stack* s1,int val){
if(isFull(s1)){
else{
s1->top++;
s1->arr[s1->top]=val;
//pop operation
if(isEmpty(s1)){
else{
int val=s1->arr[s1->top];
s1->top--;
int main(){
// struct stack s;
//call by reference
17
struct stack *sp=(struct stack*)malloc(sizeof(struct stack));
//structure point will store address of the structure
sp->top=-1;
sp->arr=(int *)malloc(sp->size*sizeof(int));
printf("%d\n",isFull(sp)); //false
printf("%d\n",isEmpty(sp)); //true
push(sp,2); //top=0
push(sp,4); //top=1
push(sp,5); //top=2
printf("%d\n",isFull(sp)); //true
printf("%d\n",isEmpty(sp)); //false
pop(sp); //top=1
pop(sp); //top=0
pop(sp); //top=-1
printf("%d\n",isFull(sp)); //false
printf("%d\n",isEmpty(sp)); //true
return 0;
18
Output:
PS D:\DSA LAB> cd "d:\DSA LAB\" ; if ($?) { gcc stackOperation.c -o stackOperation } ; if
($?) { .\stackOperation }
Enter the size of stack you want:
3
0
1
Stack Overflow! cannot push 3 to the stack
1
0
Popped stack element is : 5
Popped stack element is : 4
Popped stack element is : 2
Stack Underflow!, No element available in stack to pop
0
1
PS D:\DSA LAB>
Assignments:
Viva Questions:
1. What is stack?
2. Give real time example of stack?
3. What is meant by push and pop?
4. When overflow will occur in stack?
5. When underflow will occur in stack?
6. What is the significance of top pointer?
19
EXPERIMENT No.4
Aim:- Write a program to convert infix expression into postfix
expression using stack.
Theory:
Suppose Q is an arithmetic exp written in infix notation. This algorithm finds the equivalent
postfix expression P.
1. Push “(“onto stack and add “)” to the end of Q.
2. Scan Q from left to right and repeat steps 3 to 6 for each element of Q until the stack is
empty.
3. If an operand is encountered add it to p.
4. If a left parenthesis is encountered push it onto stack.
5. If an operator is encountered then:
a. Repeatedly pop from stack.
b. add operator to stack.
6. If right parenthesis is encountered then:
a. Repeatedly pop from stack.
b. Remove the left parenthesis.
7. Exit.
Source code:
#include<stdio.h>
#include<ctype.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>
#define SIZE 20
void main()
20
{
clrscr();
printf(“\n\ t Program to covert infix expression into postfix expression; “);
printf(“\n\t Enter your expression & to quit enter fullstop(.) :”);
while((c=getc(stdin))!=’\n’)
{
A[m]=c;
m++;
}
l=m;
infix_to_postfix ();
getch();
}
S->top = 0 ;
}
/********** Function Definition ends **********/
/********** Pushing an element in stack **********/
/********** Function Definition begins **********/
void push(stack *S, char A[])
{
if(S->top >= SIZE)
{
printf(“\nStack is full”);
}
else
{
S->item[S->top] = A[m];
S->top = S->top+1;
}
}
/********** Function Definition ends **********/
/********** Popping an element from stack **********/
/********** Function Definition begins **********/
void pop(stack *S)
{
if (S->top < 0)
{
printf(“\n Stack is empty”);
}
else
{
if(S->top >=0)
21
{
S->top = S->top-1;
if(S->item[S->top]!=’(‘)
printf(“%c”,S->item[S->top]);
}
}
}
/********** Function Definition ends **********/
/********** Infix to Postfix conversion **********/
/********** Function Definition begins **********/
void infix_to_postfix()
{
stack S;
create(&S);
m=0;
while(m<l)
{
switch(A[m])
{
case ‘+’ :
case ‘-’ :
while(S.item[S.top-1] ==’-’ || S.item[S.top-1] ==’+’ ||S.item[S.top-1]
==’*’ ||S.item[S.top-1] ==’/’ ||S.item[S.top-1] ==’^’ && S.item[S.top-1] !=’(‘)
pop(&S);
push(&S,A);
++m;
break;
case ‘/’ :
case ‘*’ :
while(S.item[S.top-1] ==’*’ ||S.item[S.top-1] ==’/’ ||S.item[S.top-1]
==’^’ && S.item[S.top-1] !=’(‘)
pop(&S);
push(&S,A);
++m;
break;
case ‘^’ :
push(&S,A);
++m;
break;
case ‘(‘ :
push(&S,A);
++m;
break;
case ‘)’ :
while(S.item[S.top-1]!=’(‘)
pop(&S);
pop(&S);
++m;
break;
22
case ‘.’ :
while (S.top >= 0)
pop(&S);
exit(0);
default : if(isalpha(A[m]))
{
printf(“%c”,A[m]);
++m;
break;
}
else
{
printf(“\n some error”);
exit(0);
}
}
}
}
/********** Function Definition ends **********/
Output:
Assignments:
Viva Questions:
1. What is stack?
2. What are the operations performed on stack?
3. Explain push and pop operations of stack.
4. What is meant by binary expression?
5. What is meant by prefix expression?
6. What is meant by infix expression?
7. What is meant by postfix expression?
8. Write different applications of stack?
9. Convert the following infix expression into postfix expression
A + (B * C –(D / E ^ F) * G ) * H
23
EXPERIMENT No. 5
Aim: - Write a program to perform following operations in linear
queue-addition, deletion, and traversing.
Theory:
Procedure createQ(Q):
The above procedure creates an empty queue. Variable front and rear set to value – 1.
24
else goto step 2.
Step 2 [Deletion of an element]
Set temp 🡨 Q (item [Q (front)]).
Step 3 [setting front and rear, if queue is empty]
if Q (front) = Q(rear)) then
Set Q (front) 🡨 – 1.
Set Q (rear) 🡨 – 1.
else
Set Q(front) 🡪 Q(front) + 1.
Step 4 [return value at the time of call]
return (temp).
Source code:
#include<stdio.h>
#include<stdlib.h>
struct Queue {
int size;
int f;
int r;
int * arr;
};
int isFull(struct Queue* q){
if(q->r==q->size-1){
return 1;
}
else{
return 0;
}
}
int isEmpty(struct Queue* q){
if(q->r==q->f){
return 1;
}
else{
return 0;
}
}
void enqueue(struct Queue * q,int val){
if(isFull(q)){
25
printf("The queue is full\n");
}
else{
q->r++;
q->arr[q->r]=val;
}
}
int dequeue(struct Queue *q){
int a=-1;
if(isEmpty(q)){
printf("Queue is Empty \n");
}
else{
q->f++;
a=q->arr[q->f];
}
return a;
}
int main(){
struct Queue q;
//q=(struct Queue *)malloc(sizeof(struct Queue));
printf("Enter the size of queue you want to create \n");
scanf("%d",&q.size);
q.f=q.r=-1;
q.arr=(int *)malloc(q.size*sizeof(int));
if(isEmpty(&q)){
printf("Queue is empty\n");
}
// Enqueue few elements
enqueue(&q,5); //&q because we have to give value to pointer and
pointer store address which we get using &
enqueue(&q,7);
enqueue(&q,8);
enqueue(&q,10);
printf("dequeueing element %d \n",dequeue(&q));
printf("dequeueing element %d \n",dequeue(&q));
printf("dequeueing element %d \n",dequeue(&q));
printf("dequeueing element %d \n",dequeue(&q));
return 0;
}
26
Output:
Assignment:
1. Consider the following linear queue of characters, implemented as array of six memory
locations FRONT = 2, REAR = 3, QUEUE: ,A, D, , , . describe the queue as the
following operation takes place: ADD “S”.
Viva Questions:
27
EXPERIMENT No.6
Aim:- Write a program to perform following operations
operation in circular queue- addition, deletion, and traversing.
Theory:
Procedure EnCqueue (Q, data):
This procedure inserts value data in circular queue.
Step 1 [If Empty]
if (CQ (front = – 1) then
{
Set CQ (front) 🡨 0.
Set CQ (rear) 🡨 0 .
}
elseif (CQ (rear) = (SIZE – 1) then
Set CQ (rear) = 0.
else
Set CQ(rear) 🡨 CQ(rear) + 1.
Step 2 [Inserts value at rear end]
Set CQ (item [CQ (rear)]) 🡨 data.
Step 3 return at the point of call
Return.
28
Step 1 [setting value to NULL]
Set Q(front) 🡨 NULL.
Set Q(rear) 🡨 NULL.
Step 2 [return at the point of call]
Return.
Source code:
#include<stdio.h>
#include<conio.h>
#define SIZE 20
void main()
{
int data,ch;
circularQ CQ;
clrscr();
create(&CQ);
printf(“\n\t\t Program shows working of circular queue”);
do
{
printf(“\n\t\t Menu”);
printf(“\n\t\t 1: encequeue”);
printf(“\n\t\t 2: decqueue “);
printf(“\n\t\t 3: exit. “);
printf(“\n\t\t Enter choice : ”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“\n Enter data:”);
scanf(“%d”,&data);
encqueue(&CQ,data);
printf(“\n Elements in a circular queue are : ”);
29
display(&CQ);
continue;
case 2:
decqueue(&CQ,data);
if (CQ.front==0)
continue;
else
{
printf(“\n Elements in a circular queue are : ”);
display(&CQ);
continue;
}
case 3: printf(“\n finish”); return;
}
}while(ch!=3);
getch();
}
30
CQ->rear = 1;
CQ->item[CQ->rear] = data;
}
else
{
CQ->rear = CQ->rear +1;
CQ->item[CQ->rear] = data;
}
}
}
/********** Function Definition ends **********/
31
}
printf(“\n”);
}
else
if(CQ->front == (CQ->rear+1))
{
for(x=CQ->rear;x<=SIZE;x++)
{
printf(“%d\t”,CQ->item[x]);
}
printf(“\n”);
}
else
if(CQ->front > (CQ->rear +1))
{
for(x=1;x<=CQ->rear;x++)
{
printf(“%d\t”,CQ->item[x]);
}
for(x=CQ->front;x<SIZE;x++)
{
printf(“%d\t”,CQ->item[x]);
}
printf(“\n”);
}
else
{
for(x=CQ->front;x<=CQ->rear;x++)
{
printf(“%d\t”,CQ->item[x]);
}
printf(“\n”);
}
}
/********** Function Definition ends **********/
Output:
Program shows working of circular queue
Menu
1: encequeue
2: decqueue
3: exit.
Enter choice : 1
32
Enter data : 11
Elements in a circular queue are : 11
Menu
1: encequeue
2: decqueue
3: exit.
Enter choice :1
Enter data : 22
Elements in a circular queue are : 11 22
Menu
1: encequeue
2: decqueue
3: exit.
Enter choice :1
Enter data: 33
Elements in a circular queue are : 11 22 33
Menu
1: encequeue
2: decqueue
3: exit.
Enter choice : 2
Element 11 is deleted :
Elements in a circular queue are :22 33
Menu
1: encequeue
2: decqueue
3: exit.
Enter choice :2
Element 22 is deleted :
Elements in a circular queue are :33
Menu
1: encequeue
2: decqueue
3: exit.
Enter choice :2
Element 33 is deleted :
Circular queue is empty
Menu
1: encequeue
2: decqueue
3: exit.
Enter choice: 3
Assignment:
33
1. Consider the following circular queue of characters, implemented as array of six memory
locations FRONT = 2, REAR = 3, QUEUE: ,A, D, , , . Describe the queue as the
following operation takes place: ADD “S”.
Viva Questions:
34
EXPERIMENT No.7
Aim: - Write a program to perform following operations in
double ended queue addition , deletion , and traversing.
Theory:
Function Dequeue (Q):
The above function deletes node from the front of the list. A call to FreeNode Function is
made in order to return the memory to the available list.
Step 1 Initialization.
Set temp 🡨 Q(front (item)).
Set p 🡨 Q(front).
Step 2 Checking for single element.
if (Q (front) = Q (rear) then
{
Set Q (front) 🡨 NULL.
Set Q (rear) 🡨 NULL.
}
else
{
Set Q (front) 🡨Q(front (link)).
Step 3 Calling FreeNode, and returning value of temp.
call to FreeNode ( )
return.
Source code:
#include<stdio.h>
#include<conio.h>
#define SIZE 20
35
int delete_rear(deque *, int);
/********** Function Declaration ends **********/
void main()
{
int x,data,ch;
deque DQ;
clrscr();
create(&DQ);
printf(“\n\t\t Program shows working of double ended queue”);
do
{
printf(“\n\t\t Menu”);
printf(“\n\t\t 1: insert at rear end”);
printf(“\n\t\t 2: insert at front end”);
printf(“\n\t\t 3: delete from front end”);
printf(“\n\t\t 4: delete from rear end”);
printf(“\n\t\t 5: exit. “);
printf(“\n\t\t Enter choice : ”);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
if (DQ.rear >= SIZE)
{
printf(“\n Deque is full at rear end”);
continue;
}
else
{
printf(“\n Enter element to be added at rear end : ”);
scanf(“%d”,&data);
insert_rear(&DQ,data);
printf(“\n Elements in a deque are : ”);
display(&DQ);
continue;
}
case 2:
if (DQ.front <=0)
{
printf(“\n Deque is full at front end”);
continue;
}
else
{
printf(“\n Enter element to be added at front end : ”);
scanf(“%d”,&data);
insert_front(&DQ,data);
36
printf(“\n Elements in a deque are : ”);
display(&DQ);
continue;
}
case 3:
x = delete_front(&DQ,data);
if (DQ.front==0)
{
continue;
}
else
{
printf(“\n Elements in a deque are : ”);
display(&DQ);
continue;
}
case 4:
x = delete_rear(&DQ,data);
if (DQ.rear==0)
{
continue;
}
else
{
printf(“\n Elements in a deque are : ”);
display(&DQ);
continue;
}
case 5: printf(“\n finish”); return;
}
}while(ch!=5);
getch();
}
37
{
DQ->item[DQ->rear] = data;
DQ->rear = DQ->rear +1;
}
else
{
DQ->item[DQ->rear] = data;
DQ->rear = DQ->rear +1;
}
}
/********** Function Definition ends **********/
38
/********** Deleting element from rear end **********/
/********** Function Definition begins **********/
int delete_rear(deque *DQ, int data)
{
if (DQ->rear == 0)
{
printf(“\n Underflow”);
return(0);
}
else
{
DQ->rear = DQ->rear -1;
data = DQ->item[DQ->rear];
printf(“\n Element %d is deleted from rear: ”,data);
}
if (DQ->front==DQ->rear)
{
DQ->front =0;
DQ->rear = 0;
printf(“\n Deque is empty(rear end)”);
}
return data;
}
/********** Function Definition ends **********/
Output:
Program shows working of double ended queue
Menu
1: insert at rear end
39
2: insert at front end
3: delete from front end
4: delete from rear end
5: exit.
Enter choice : 1
Enter element to be added at rear end : 11
Elements in a deque are : 11
Menu
1: insert at rear end
2: insert at front end
3: delete from front end
4: delete from rear end
5: exit.
Enter choice :1
Enter element to be added at rear end : 22
Elements in a deque are : 11 22
Menu
1: insert at rear end
2: insert at front end
3: delete from front end
4: delete from rear end
5: exit.
Enter choice : 1
Enter element to be added at rear end : 33
Elements in a deque are : 11 22 33
Menu
1: insert at rear end
2: insert at front end
3: delete from front end
4: delete from rear end
5: exit.
Enter choice : 2
Deque is full at front end
Menu
1: insert at rear end
2: insert at front end
3: delete from front end
4: delete from rear end
5: exit.
Enter choice :3
Element 11 is deleted from front :
Elements in a deque are : 22 33
Menu
1: insert at rear end
2: insert at front end
40
3: delete from front end
4: delete from rear end
5: exit.
Enter choice : 2
Element 11 is deleted from front :
Elements in a deque are : 22 33
Menu
1: insert at rear end
2: insert at front end
3: delete from front end
4: delete from rear end
5: exit.
Enter choice : 5
Assignment:
1. Consider the following deque of characters, implemented as array of six memory locations
FRONT = 2, REAR = 3, QUEUE: ,A, D, , , . Describe the queue as the following
operation takes place: ADD “S”.
Viva Questions:
1) What is a deque?
2) How deque is stored in memory.
3) What is the difference between circular queue and double ended queue?
4) What is the state of rear and front pointer in deque?
5) What will happen if front=null in case of deque?
41
EXPERIMENT No. 8
Aim: - Write a program to perform following in singly linked list-
creation, insertion, and deletion .
Theory:
Function GetNode ( ):
This procedure provides ‘new’, a pointer to a free node from the available list. If no node
is available, then it displays an error message and return NULL
Step 1 [checking NULL].
if (avail = NULL) then
message : “overflow”.
return (NULL).
Step 2 [Adjusting pointers]
Set new 🡨 avail.
Set new 🡨 Next (avail).
Step 3 [return at the point of call]
return (new).
42
if (START = NULL) then
return true.
else
return false.
43
Step 4 [Insertion at the beginning.]
Set Next (new) 🡨 START.
Set START 🡨 new.
return (START).
Step 5 [Insertion at desired position other than beginning.]
Set count 🡨 1.
Set keep 🡨 START.
loop
while (count 🡨 pos –1)
Set keep🡨 Next (keep).
Set count 🡨 count + 1.
End of loop.
Step 6 [Setting of pointers]
Set Next (new) 🡨 Next (keep).
Set Next (keep) 🡨 new.
Step 7 [Return at the point of call.]
Return(start).
44
Set keep 🡨 start.
loop
while (count 🡨 pos –1)
Set prev 🡨keep.
Set keep 🡨 Next (keep).
Set count 🡨 count + 1.
End loop.
Step 5 [Setting of pointers]
Set Next (prev) 🡨 Next (keep).
Step 6 [Returning back the memory]
Source code:
#include<stdio.h>
#include<stdlib.h>
struct Node{
int data;
};
ptr = ptr->next;
45
int main(){
head->data=7;
head->next=second;
second->data=11;
second->next=third;
third->data=8;
third->next=NULL;
linkedListTraversal(head);
linkedListTraversal(second);
return 0;
46
Output:
PS D:\DSA LAB> cd "d:\DSA LAB\.vscode\" ; if ($?) { gcc linkedListCreation.c -o
linkedListCreation } ; if ($?) { .\linkedListCreation }
Element: 7
Element: 11
Element: 8
print after second node
Element: 11
Element: 8
PS D:\DSA LAB\.vscode>
#include<stdlib.h>
struct Node{
int data;
};
ptr = ptr->next;
47
struct Node * insertAtFirst(struct Node * head,int data){
ptr->next=head;
ptr->data=data;
head=ptr;
//head is changed
return head;
int i=0;
while(i!=index-1){
p=p->next;
i++;
ptr->next=p->next;
ptr->data=data;
p->next=ptr;
return head;
while(p->next!=NULL){
p=p->next;
48
}
ptr->next=NULL;
ptr->data=data;
p->next=ptr;
return head;
ptr->next=previousNode->next;
ptr->data=data;
previousNode->next=ptr;
return head;
int main(){
49
//link first and second node
head->data=7;
head->next=second;
second->data=11;
second->next=third;
third->data=16;
third->next=fourth;
fourth->data=8;
fourth->next=NULL;
linkedListTraversal(head);
head=insertAfterNode(head,second,13);
linkedListTraversal(head);
head=insertAtFirst(head,5);
linkedListTraversal(head);
head=insertAtIndex(head,9,2);
linkedListTraversal(head);
head=insertAtEnd(head,15);
linkedListTraversal(head);
return 0;
50
Output:
PS D:\DSA LAB> cd "d:\DSA LAB\.vscode\" ; if ($?) { gcc linkedListInsertion.c -o
linkedListInsertion } ; if ($?) { .\linkedListInsertion }
Element: 7
Element: 11
Element: 16
Element: 8
after insertion of node after second node
Element: 7
Element: 11
Element: 13
Element: 16
Element: 8
after insertion at beginning
Element: 5
Element: 7
Element: 11
Element: 13
Element: 16
Element: 8
after insertion at between index 2
Element: 5
Element: 7
Element: 9
Element: 11
Element: 13
Element: 16
Element: 8
after insertion at End
Element: 5
Element: 7
51
Element: 9
Element: 11
Element: 13
Element: 16
Element: 8
Element: 15
PS D:\DSA LAB\.vscode>
#include<stdlib.h>
struct Node{
int data;
};
ptr = ptr->next;
52
head=head->next;
free(ptr);
//head is changed
return head;
int i=0;
while(i!=index-1){
p=p->next;
i++;
p->next=q->next;
free(q);
//head is changed
return head;
while (q->next!=NULL)
p=p->next;
q=q->next;
53
p->next=NULL;
free(q);
//head is changed
return head;
p=p->next;
q=q->next;
if(q->data==value){
p->next=q->next;
free(q);
return head;
int main(){
54
head=(struct Node *)malloc(sizeof(struct Node));
head->data=7;
head->next=second;
second->data=11;
second->next=third;
third->data=16;
third->next=fourth;
fourth->data=8;
fourth->next=fifth;
fifth->data=1;
fifth->next=NULL;
linkedListTraversal(head);
head=deleteFirst(head);
linkedListTraversal(head);
head=deleteIndex(head,2);
linkedListTraversal(head);
head=deleteEnd(head);
55
printf("After deleting node at End:\n");
linkedListTraversal(head);
head=deleteValue(head,16);
linkedListTraversal(head);
head=deleteValue(head,3);
linkedListTraversal(head);
return 0;
Output:
PS D:\DSA LAB> cd "d:\DSA LAB\.vscode\" ; if ($?) { gcc LinkedListDeletion.c -o
LinkedListDeletion } ; if ($?) { .\LinkedListDeletion }
Element: 7
Element: 11
Element: 16
Element: 8
Element: 1
After deleting first node:
Element: 11
Element: 16
Element: 8
Element: 1
After deleting node at index: 2
Element: 11
Element: 16
Element: 1
After deleting node at End:
Element: 11
56
Element: 16
After deleting given value from linked list:
Element: 11
PS D:\DSA LAB\.vscode>
Assignments:
Viva Questions:
1. What is a linked list?
2. Give the importance of linked list?
3. Can we implement stack and queue using linked list?
4. State applications of singly linked list?
5. What is the significance of pointers in linked list?
57
EXPERIMENT No.9
Aim:- Write a program to perform creation , insertion , deletion
of doubly linked list.
Theory:
Procedure Dcreate (START, END)
This procedure creates an empty list. The pointer variable START and END are
assigned a sentinel value to indicate the list is empty in the beginning.
Step1 Initialization.
Set START ← NULL
Source code:
#include <stdio.h>
#include <malloc.h>
#include<process.h>
void main()
{
node *left=NULL,*right;
int item,pos,ch;
printf(“\n\t\tProgram for doubly linked list\n”);
do
{
58
printf(“\n\t\tMenu”);
printf(“\n\t\t1.Create”);
printf(“\n\t\t2.Insert”);
printf(“\n\t\t3.Delete”);
printf(“\n\t\t4.Display”);
printf(“\n\t\t5.Exit”);
printf(“\n\t\tEnter choice : “);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
left = DLcreation(&right);
break;
case 2:
printf(“\nEnter data :”);
scanf(“%d”,&item);
do
{
printf(“\nEnter position of insertion :”);
scanf(“%d”,&pos);
}while(pos < 1);
DLinsertion(&left,&right,item,pos);
break;
case 3:
DLdeletion(&left,&right);
break;
case 4:
printf(“\n\t**** Doubly linked list *****\n”);
DLdisplay(left,right);
break;
case 5:
exit(0);
default:
printf(“\n Wrong Choice”);
}
}while(ch!=5);
printf(“\n”);
}
59
{
printf(“\n\t\tMenu”);
printf(“\n\t\t1.Add node”);
printf(“\n\t\t2.Quit”);
printf(“\n\t\tEnter choice : “);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“\n Enter data:”);
scanf(“%d”,&item);
new_node = (node *)malloc(sizeof(node));
new_node->data = item;
new_node->rlink = NULL;
if(left == NULL)
{
new_node->llink = NULL;
left = new_node;
}
else
{
new_node->llink = (*right);
(*right)->rlink = new_node;
}
(*right) = new_node;
if(left != NULL)
(*right) = new_node;
break;
case 2:
break;
default:
printf(“\n Wrong Choice”);
}
}while(ch!=2);
return left;
}
/********** Function Definition ends **********/
60
new_node->data = item;
new_node->rlink = *start;
new_node->llink = NULL;
if((*start) != NULL)
(*start)->llink = new_node;
else
(*right) = new_node;
*start = new_node;
}
else
{
temp = *start;
i = 2;
while((i < pos) && (temp->rlink != NULL))
{
temp = temp->rlink;
++i;
}
new_node = (node *)malloc(sizeof( node));
new_node->data = item;
new_node->rlink = temp->rlink;
if(temp->rlink != NULL)
temp->rlink->llink = new_node;
new_node->llink = temp;
temp->rlink = new_node;
}
if(new_node->rlink == NULL)
*right = new_node;
}
/********** Function Definition ends **********/
61
(*start)->llink = NULL;
}
}
else
{
temp = *start;
prec = NULL;
while((temp->rlink != NULL) && (temp->data != item))
{
prec = temp;
temp = temp->rlink;
}
if(temp->data != item)
printf(“\n Data in the list not found\n”);
else
{
if(temp == *right)
*right = prec;
else
temp->rlink->llink = temp->llink;
prec->rlink = temp->rlink;
}
}
}
else
printf(“\n!!! Empty list !!!\n”);
return;
}
/********** Function Definition ends **********/
62
}
/********** Function Definition ends **********/
Output:
Program for doubly linked list
Menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter choice : 1
Menu
1.Add node
2.Quit
Enter choice : 1
Enter data:11
Menu
1.Add node
2.Quit
Enter choice : 1
Enter data:22
Menu
1.Add node
2.Quit
Enter choice : 1
Enter data:33
Menu
1.Add node
2.Quit
Enter choice : 1
Enter data:44
Menu
1.Add node
2.Quit
Enter choice : 1
Enter data:55
Menu
1.Add node
2.Quit
Enter choice : 2
63
Menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter choice : 2
Menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter choice : 2
Enter data :99
Enter position of insertion :3
Menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter choice :4
**** Doubly linked list *****
***** Traverse in Forward direction *****
left->11-> 22-> 99-> 33-> 44-> 55-> right
***** Traverse in Backward direction *****
right->55-> 44-> 33-> 99-> 22-> 11-> left
Menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter choice : 3
Element to be deleted :33
Menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter choice : 4
**** Doubly linked list *****
64
***** Traverse in Forward direction *****
left->11-> 22-> 99-> 44-> 55-> right
***** Traverse in Backward direction *****
right->55-> 44-> 99-> 22-> 11-> left
Menu
1.Create
2.Insert
3.Delete
4.Display
5.Exit
Enter choice :5
Assignments:
Viva Questions:
1. What is a linked list?
2. Give the importance of linked list?
3. Can we implement stack and queue using linked list?
4. State applications of doubly linked list?
5. What is the significance of pointers in linked list?
65
EXPERIMENT No. 10
Theory:-
Linked lists are widely used to represent and manipulate polynomials. Polynomials are the
expressions containing number of terms with non zero coefficients and exponents. Consider
the following polynomial.
p(X)=anxen+an-1xen-1+…+a1x1e+a
where ai a are nonzero coefficients.
ei a are exponents such that
In the linked representation of polynomials, each term is considered as a node. And such a
node contains three fields.
1.Coefficent field 2.Exponent field 3.Link field.
The coefficient field holds the value of the coefficient of a term and the exponent field
contains the exponent value of that term and the exponent field contains the exponent value
of that term. And the link field contains the addresses of the next term in the polynomial.
The logical representation of the above node is given below:
struct polynode
{
int coeff;
int expo;
struct polynode *ptr;
};
typedef struct polynode PNODE;
Two polynomials can be added. And the steps involved in adding two polynomials are given
below:
1.Read the number of terms in the first polynomial P.
2.Read the coefficients and exponents of the first polynomial.
3.Read the number of terms in the second polynomial Q.
4.Read the coefficients and exponents in the second polynomial.
5.Set the temporary pointers p and q to traverse the two polynomials respectively.
6.Compare the exponents of two polynomials starting from the first nodes.
(a) If both exponents are equal then add the coefficients and store it in the resultant linked
list.
(b) If the exponent of the current term in the first polynomial P is less than the exponent of
the current term of the second polynomial is added to the resultant linked list. And move the
pointer q to point to the next node in the second polynomial Q.
(c) If the exponent of the current term in the first polynomial P is greater than the exponent of
the current term in the second polynomial Q then the current term of the first polynomial is
added to the resultant linked list. And move the pointer p to the next node.
66
(d) Append the remaining nodes of either of the polynomials to the resultant linked list.
Source Code:-
#include<stdio.h>
#include<conio.h>
#include<limits.h>
int select();
struct rec
{
float coef;
int exp;
struct rec *next;
};
struct rec *rear;
struct rec *create(struct rec *list);
void *add(struct rec *first,struct rec *second);
struct rec *insert(double coef,int exp,struct rec *rear);
void *display(struct rec *list);
int nodes;
void main()
{
struct rec *first=NULL,*second=NULL;
int choice;
do
{
choice=select();
switch(choice)
{
case 1: first=create(first);continue;
case 2: second=create(second);continue;
case 3: add(first,second);continue;
case 4: puts("END");exit(0);
}
}while(choice!=4);
}
int select()
{
int selection;
do
{
puts("Enter 1: create the first list");
puts("Enter 2: create the second list");
puts("Enter 3: add the two list");
puts("Enter 4: END");
puts("Entr your choice");
scanf("%d",&selection);
67
}while((selection<1)||(selection>4));
return (selection);
}
68
second=second->next;
}
Else
if(first->exp>second->exp)
{
rear=insert(first->coef,first->exp,rear);
first=first->next;
}else
{
rear=insert(second->coef,second->exp,rear);
second=second->next;
}
}
for(;first;first=first->next)
rear=insert(first->coef,first->exp,rear);
for(;second;second=second->next)
rear=insert(second->coef,second->exp,rear);
rear->next=NULL;
display(end->next);
free(end);
}
void *display(struct rec *head)
{
while(head!=NULL)
{
printf("%2lf",head->coef);
printf("%2d",head->exp);
head=head->next;
}
printf("\n");
}
struct rec *insert(double coef,int exp,struct rec *rear)
{
rear->next=(struct rec *)malloc(sizeof(struct rec));
rear=rear->next;
rear->coef=coef;
rear->exp=exp;
return(rear);
}
Output:
69
Enter 4 : END
Enter your choice
1
Enter coefs & exp : exp in descending order : to quit enter 0 for exp
Enter coefficient
5
Enter exponent
4
Enter coefficient
7
Enter exponent
9
Enter coefficient
1
Enter exponent
3
Enter coefficient
0
Enter 1 : Create the first list
Enter 2 : Create the second list
Enter 3 : Add the two list
Enter 4 : END
Enter your choice
2
Enter coefs & exp : exp in descending order : to quit enter 0 for exp
Enter coefficient
9
Enter exponent
3
Enter coefficient
2
Enter exponent
2
Enter coefficient
11
Enter exponent
1
Enter coefficient
5
Enter exponent
0
Invalid exponent
Enter 1 : Create the first list
Enter 2 : Create the second list
Enter 3 : Add the two list
Enter 4 : END
Enter your choice
3
70
5.000000 47.000000 96.000000 32.000000 211.000000 1
Enter 1 : Create the first list
Enter 2 : Create the second list
Enter 3 : Add the two list
Enter 4 : END
Enter your choice
4
Assignments:-
Viva Questions:-
1. What is a polynomial?
2. What is a two variable polynomial?
3. Give pictorial representation of addition of two polynomials.
4. Can overflow occur in link list?
5. What is dynamic memory allocation?
71
EXPERIMENT No. 11
Theory:-
Pushing:-
Popping:-
Source Code:-
#include <stdio.h>
#include <malloc.h>
#include<process.h>
typedef struct link_tag
{
int data;
struct link_tag *link;
}node;
72
/********** Function Declaration ends **********/
void main()
{
node *start=NULL;
int ch;
do
{
printf(“\n\t\tMenu”);
printf(“\n\t\t1.Push”);
printf(“\n\t\t2.Pop”);
printf(“\n\t\t3.Display”);
printf(“\n\t\t4.Exit”);
printf(“\n\t\tEnter choice : “);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
start = push(start);
break;
case 2:
start = pop(start);
break;
case 3:
printf(“\n\t**** Stack *****\n”);
display(start);
break;
case 4:
exit(0);
default:
printf(“\nwrong choice : ”);
}
}
while (ch!=4);
printf(“\n”);
}
73
printf(“Enter an data to be pushed : “);
scanf(“%d”,&item);
if(p == NULL)
printf(“\n***** Empty *****\n”);
else
{
printf(“Popped data = %d\n”,p->data);
temp = p->link;
free(p);
p = temp;
if (p == NULL)
printf(“\n***** Empty *****\n”);
}
return(p);
}
/********** Function Definition ends **********/
74
/********** Function Definition ends **********/
Output:
Program of stack using linked list
Menu
1.Push
2.Pop
3.Display
4.Exit
Enter choice : 1
Enter an data to be pushed : 11
Menu
1.Push
2.Pop
3.Display
4.Exit
Enter choice : 1
Enter an data to be pushed : 22
Menu
1.Push
2.Pop
3.Display
4.Exit
Enter choice : 1
Enter an data to be pushed : 33
Menu
1.Push
2.Pop
3.Display
4.Exit
Enter choice : 3
**** Stack *****
75
1.Push
2.Pop
3.Display
4.Exit
Enter choice : 2
Popped data = 22
Menu
1.Push
2.Pop
3.Display
4.Exit
Enter choice : 3
**** Stack *****
Top-> 11->NULL
Menu
1.Push
2.Pop
3.Display
4.Exit
Enter choice :2
Popped data = 11
***** Empty *****
Menu
1.Push
2.Pop
3.Display
4.Exit
Enter choice : 4
Assignments:-
Viva Questions:-
1. What is a stack?
2. What are push and pop operations?
3. Give practical implementation of stack.
4. Can overflow occur in link list?
5. What is dynamic memory allocation?
76
11.2 Linked Queue:
Theory:-
Pushing:-
1. Input the data element to be pushed.
2. Create a NewNode.
3. NewNode 🡪 DATA=DATA.
4. NewNode 🡪 Next=NULL.
5. If (REAR not equal to NULL)
(a) REAR 🡪 Next=NewNode.
6. REAR=NewNode.
7. Exit.
Popping:-
1. If (FRONT is equal to NULL)
(a) Display “The Queue is empty”.
2. Else
(a) Display “The popped element is FRONT🡪DATA”.
(b) If (FRONT is not equal to REAR)
(i) FRONT=FRONT🡪Next.
(c) Else
FRONT=NULL.
3. EXIT.
Source Code:-
#include <stdio.h>
#include <malloc.h>
#include<process.h>
void main()
{
node *front = NULL, *rear = NULL;
int ch,item;
77
do
{
printf(“\n\t\tMenu”);
printf(“\n\t\t1.enqueue”);
printf(“\n\t\t2.dequeue”);
printf(“\n\t\t3.display”);
printf(“\n\t\t4.exit”);
printf(“\n\t\tEnter choice : “);
scanf(“%d”,&ch);
switch(ch)
{
case 1:
printf(“Enter an data to be enqueued : “);
scanf(“%d”,&item);
enqueue(&front,&rear,item);
break;
case 2:
dequeue(&front);
break;
case 3:
printf(“\n\t**** Queue *****\n”);
display(front);
break;
case 4:
exit(0);
default:
printf(“\n wrong choice:”);
}
}
while (ch!=4);
printf(“\n”);
}
if ((*front) == NULL)
{
(*front) = new_node;
(*rear) = new_node;
}
78
else
{
(*rear)->link = new_node;
(*rear) = new_node;
}
return;
}
/********** Function Definition ends **********/
if((*front) != NULL)
{
temp = *front;
(*front) = (*front)->link;
free(temp);
}
return;
}
/********** Function Definition ends **********/
Output:
Program of queue using linked list
Menu
1.enqueue
2.dequeue
3.display
4.exit
Enter choice : 1
Enter an data to be enqueued : 11
79
Menu
1.enqueue
2.dequeue
3.display
4.exit
Enter choice : 1
Enter an data to be enqueued : 22
Menu
1.enqueue
2.dequeue
3.display
4.exit
Enter choice : 1
Enter an data to be enqueued : 33
Menu
1.enqueue
2.dequeue
3.display
4.exit
Enter choice : 3
**** Queue *****
Root-> 11-> 22-> 33->NULL
Menu
1.enqueue
2.dequeue
3.display
4.exit
Enter choice : 2
Menu
1.enqueue
2.dequeue
3.display
4.exit
Enter choice : 2
Menu
1.enqueue
2.dequeue
3.display
4.exit
Enter choice : 3
**** Queue *****
Root-> 33->NULL
Menu
1.enqueue
2.dequeue
3.display
4.exit
Enter choice : 2
Menu
80
1.enqueue
2.dequeue
3.display
4.exit
Enter choice :3
**** Queue *****
Root->NULL
Menu
1.enqueue
2.dequeue
3.display
4.exit
Enter choice : 4
Assignments:-
Viva Questions:-
81
EXPERIMENT No. 12
Aim:- Write programs to perform Insertion sort, Selection sort
and Bubble sort.
Source Code:-
#include<stdio.h>
for(int i=0;i<n;i++){
printf("%d ",A[i]);
printf("\n");
82
int indexOfMin,temp;
for(int j=i+1;j<=n-1;j++){
if(A[j]<A[indexOfMin]){
indexOfMin=j;
temp=A[indexOfMin];
A[indexOfMin]=A[i];
A[i]=temp;
printArray(A,n);
int main()
//passing
// 0 1 2 3 4 5 index
int A[]={12,54,65,7,23,9};
int n=6;
83
printf("Before sorting: \n");
selectionSort(A,n);
printArray(A,n);
return 0;
Output:
PS D:\DSA LAB> cd "d:\DSA LAB\" ; if ($?) { gcc selection_sort.c -o selection_sort } ; if
($?) { .\selection_sort }
Before sorting:
12 54 65 7 23 9
Working in pass no. :1
7 54 65 12 23 9
Working in pass no. :2
7 9 65 12 23 54
Working in pass no. :3
7 9 12 65 23 54
Working in pass no. :4
7 9 12 23 65 54
Working in pass no. :5
7 9 12 23 54 65
After sorting:
7 9 12 23 54 65
PS D:\DSA LAB>
Assignments:-
84
Viva Questions:-
1. What is sorting?
2. Differentiate between sorting and searching.
3. Give complexity of this technique.
4. What is a pass?
5. What is worst case and average case of complexity?
Step 1 Initialization.
Set l 🡨 n, P 🡨 1.
Step 2 loop
Repeat step 3, 4 while (P🡨n – 1).
Set E 🡨 0 R Initializing exchange variable.
Step 3 Comparison, loop.
Repeat for i 🡨 1, l, ..... l – 1.
if (A [i] > A[i + 1]) then
Set A [i] <--> A [i + 1] R Exchanging values.
Set E 🡨 E + 1.
Step 4 Finish, or reduce the size.
if (E = 0) then
Exit.
else
Set l 🡨 l – 1.
Source code:-
#include<stdio.h>
for(int i=0;i<n;i++){
printf("%d ",A[i]);
85
printf("\n");
int temp;
if(A[j]>A[j+1]){ //swaping
temp=A[j];
A[j]=A[j+1];
A[j+1]=temp;
printArray(A,n);
int main(){
int A[]={12,54,65,7,23,9};
int n=6;
bubblesort(A,n);
return 0;
86
Output:
PS D:\DSA LAB> cd "d:\DSA LAB\" ; if ($?) { gcc bubbleSort.c -o bubbleSort } ; if ($?) {
.\bubbleSort }
Before sorting:
12 54 65 7 23 9
Working on pass no. 1
12 54 7 23 9 65
Working on pass no. 2
12 7 23 9 54 65
Working on pass no. 3
7 12 9 23 54 65
Working on pass no. 4
7 9 12 23 54 65
Working on pass no. 5
7 9 12 23 54 65
After sorting:
7 9 12 23 54 65
PS D:\DSA LAB>
Assignments:-
Viva Questions:-
1. What is sorting?
2. Differentiate between sorting and searching.
3. Give complexity of this technique.
4. What is a pass?
5. What is worst case and average case of complexity?
87
12.3 Insertion Sort:
Theory:-
Procedure Insertionsort (A, n):
The Procedure Subalgorithm sorts the elements of an array ‘A’ in an ascending order.
The array consists of ‘n’ number of elements. The variable ‘i’ is used for index and ‘t’ is a
temporary variable.
Step 1 Loop, uptil length [A].
Repeat step 1, 2 for i 🡨 2, 3, 4, 5, --- n
Set t 🡨A[i], p 🡨 i – 1
Temporary variable is set to new value, pointer is adjusted.
Step 2 Loop, comparison
Repeat while (p > 0 and t < A[p])
Set A [p +1] 🡨A[p], p🡨p – 1.
End of step 2 loop.
Step 3 Inserting element in appropriate place
Set A [p + 1] 🡨 t.
End of step 1 loop.
Step 4 Finished.
Return.
Source Code:-
#include<stdio.h>
for(int i=0;i<n;i++){
printf("%d ",A[i]);
printf("\n");
int key,j;
for(int i=1;i<=n-1;i++){
88
printf("working in pass no. %d \n",i);
key=A[i];
j=i-1;
A[j+1]=A[j];
A[j+1]=key;
int main()
//passing
//-1 0 1 2 3 4 5
// 12| 54 65 7 23 9 i=1,key=A[1]=54,j=0
// 12 54| 65 7 23 9 i=2,key=A[2]=65,j=1
// 12 54 65| 7 23 9 i=3,key=A[3]=7,j=2
// 7 12 54 65| 23 9 i=4,key=A[4]=23,j=3
// 7 12 23 54 65| 9 i=5,key=A[5]=9,j=4
// 7 9 12 23 54 65|
int A[]={12,54,65,7,23,9};
int n=6;
89
insertionsort(A,n);
printArray(A,n);
return 0;
Output:
PS D:\DSA LAB> cd "d:\DSA LAB\" ; if ($?) { gcc insertionSort.c -o insertionSort } ; if ($?)
{ .\insertionSort }
Before sorting:
12 54 65 7 23 9
working in pass no. 1
12 54 65 7 23 9
working in pass no. 2
12 54 65 7 23 9
working in pass no. 3
7 12 54 65 23 9
working in pass no. 4
7 12 23 54 65 9
working in pass no. 5
7 9 12 23 54 65
After sorting:
7 9 12 23 54 65
PS D:\DSA LAB>
90
EXPERIMENT No. 13
Aim:- Write a program to perform Quick sort.
Theory:-
Quick_Sort(a,l,h):
a 🡪 represents the list of elements.
l 🡪 represents the position of the first element in the list(only at the starting point, it’s value
change during the execution of the function).
h 🡪 represents the position of the last element in the list(only at starting point the value of it’s
changes during the execution of the function).
Step 1: [Initially]
low=l.
high=h.
key=a[(l+h)/2][middle element of the element of the list].
Source Code:-
#include<stdio.h>
for(int i=0;i<n;i++){
printf("%d ",A[i]);
printf("\n");
91
int partition(int A[], int low, int high)
int i = low + 1;
int j = high;
int temp;
do
i++;
j--;
if (i < j)
temp = A[i];
A[i] = A[j];
A[j] = temp;
temp = A[low];
A[low] = A[j];
A[j] = temp;
return j;
92
void quickSort(int A[],int low, int high){
int partitionIndex;
if(low<high){
printArray(A,6);
int main()
{ //passing
// 0 1 2 3 4 5 index
int A[]={12,54,65,7,23,9};
int n=6;
quickSort(A,0,n-1);
printArray(A,n);
return 0;
93
Output:
PS D:\DSA LAB> cd "d:\DSA LAB\" ; if ($?) { gcc tempCodeRunnerFile.c -o
tempCodeRunnerFile } ; if ($?) { .\tempCodeRunnerFile }
Before sorting:
12 54 65 7 23 9
partition performed
7 9 12 65 23 54
partition performed
7 9 12 65 23 54
partition performed
7 9 12 54 23 65
partition performed
7 9 12 23 54 65
After sorting:
7 9 12 23 54 65
PS D:\DSA LAB>
Assignments:-
Viva Questions:-
1. What is sorting?
2. Differentiate between sorting and searching.
3. State complexity of this technique.
4. What is a pass?
5. What is worst case and average case of complexity?
94
EXPERIMENT No. 14
95
Source Code:-
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
96
}
return (node);
}
/* Driver code*/
int main()
{
struct node* root = newNode(4);
root->left = newNode(2);
root->right = newNode(5);
root->left->left = newNode(1);
root->left->right = newNode(3);
// Function call
if (isBST(root))
printf("Is BST");
else
printf("Not a BST");
return 0;
}
Output:
PS D:\DSA LAB> cd "d:\DSA LAB\" ; if ($?) { gcc heap_sort.c -o heap_sort } ; if ($?) {
.\heap_sort }
Sorted array is
5 6 7 11 12 13
PS D:\DSA LAB>
97
Assignments:-
Viva Questions:-
1. What is sorting?
2. Differentiate between sorting and searching.
3. State complexity of this technique.
4. What is a pass?
5. What is worst case and average case of complexity?
98
EXPERIMENT No. 15
99
Step 3 Copying remaining elements
if (f 🡨 second) then
Loop
Repeat while (S🡨third)
Set n 🡨n + 1.
Set temp [n] 🡨A[S].
Set S🡨S + 1.
End loop.
else
Loop
Repeat while (f < second)
Set n🡨n + 1.
Set temp [n] 🡨 A[S].
Set f 🡨 f + 1.
End of loop.
Step 4 Copying, element to original array
Loop
Repeat for f🡨1, 2, ---- n.
A [first – 1 + f] 🡨 temp [f].
End of loop.
Step 5 Finish.
Return.
Source Code:-
#include<stdio.h>
for(int i=0;i<n;i++){
printf("%d ",A[i]);
printf("\n");
int i,j,k,B[high+1];
i=low;
j=mid+1;
k=low;
100
while(i<=mid && j<=high){
if(A[i]<A[j]){
B[k]=A[i];
k++;
i++;
else{
B[k]=A[j];
k++;
j++;
while (i<=mid)
B[k]=A[i];
k++;
i++;
while(j<=high){
B[k]=A[j];
k++;
j++;
for(i=low;i<=high;i++){
A[i]=B[i];
printArray(A,high+1);
101
void mergeSort(int A[],int low, int high)
int mid;
if(low<high){
mid=(low+high)/2;
mergeSort(A,low,mid);
mergeSort(A,mid+1,high);
merge(A,mid,low,high);
int main()
//passing
//-1 0 1 2 3 4 5
// 12| 54 65 7 23 9
int A[]={9,14,4,8,7,5,6};
int n=7;
mergeSort(A,0,n-1);
return 0;
102
Output:
PS D:\DSA LAB> cd "d:\DSA LAB\" ; if ($?) { gcc merge_sort.c -o merge_sort } ; if ($?) {
.\merge_sort }
Before sorting:
9 14 4 8 7 5 6
9 14
9 14 4 8
4 8 9 14
4 8 9 14 5 7
4 8 9 14 5 6 7
4 5 6 7 8 9 14
After sorting:
4 5 6 7 8 9 14
PS D:\DSA LAB>
Assignment:-
1. Write a program to sort an array in descending order obtained after merging two
separate arrays each sorted in ascending order.
Viva Questions:-
1. What is sorting?
2. Differentiate between sorting and searching.
3. State complexity of this technique.
4. What is a pass?
5. What is worst case and average case of complexity?
103
EXPERIMENT No. 16
Aim:- Write a program to create a binary search tree and
perform insertion, deletion, and traversal.
Theory:
A particular form of binary tree suitable for searching.
A binary search tree is a binary tree that is either empty or in which each node
contains a key that satisfies the following conditions:
▪ All keys (if any) in the left subtree of the root precede the key in the
root.
▪ The key in the root precedes all keys (if any) in its right subtree.
▪ The left and right subtrees of the root are again binary search trees.
Source Code:-
16.1 Insertion
// C program to demonstrate insert
// operation in binary
// search tree.
#include <stdio.h>
#include <stdlib.h>
struct node {
int key;
struct node *left, *right;
};
104
void inorder(struct node* root)
{
if (root != NULL) {
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
// Driver Code
int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
struct node* root = NULL;
root = insert(root, 50);
insert(root, 30);
insert(root, 20);
insert(root, 40);
insert(root, 70);
insert(root, 60);
105
insert(root, 80);
return 0;
}
Output:
16.2 Deletion:
Source Code:
// C program to implement optimized delete in BST.
#include <stdio.h>
#include <stdlib.h>
struct Node {
int key;
struct Node *left, *right;
};
106
if (root != NULL) {
inorder(root->left);
printf("%d ", root->key);
inorder(root->right);
}
}
107
// We reach here when root is the node
// to be deleted.
// Find successor
struct Node* succ = root->right;
while (succ->left != NULL) {
succParent = succ;
succ = succ->left;
}
108
free(succ);
return root;
}
}
// Driver Code
int main()
{
/* Let us create following BST
50
/ \
30 70
/ \ / \
20 40 60 80 */
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);
return 0;
}
109
Output:
struct Node {
int data;
struct Node * left;
struct Node * right;
};
struct Node * createNode(int data){
struct Node * n; //crrating a node pointer
n=(struct Node *)malloc(sizeof(struct Node));//allocatio=ng the
memory in the heap
n->data=data;//setting the data
n->left=NULL;//setting the left and right child to null
n->right=NULL;
return n;//returning the creact node of type struct node
}
void preorder(struct Node * root){
if(root!=NULL){
printf("%d ",root->data);
preorder(root->left);
preorder(root->right);
}
}
110
void postorder(struct Node * root){
if(root!=NULL){
postorder(root->left);
postorder(root->right);
printf("%d ",root->data);
}
}
void inorder(struct Node * root){
if(root!=NULL){
inorder(root->left);
printf("%d ",root->data);
inorder(root->right);
}
}
int main(){
/* constructing the root node
struct Node * p;
p=(struct Node *)malloc(sizeof(struct Node));
p->data=2;
p->left=NULL;
p->right=NULL;
//constructing the 2nd node
struct Node * p1;
p1=(struct Node *)malloc(sizeof(struct Node));
p1->data=1;
p1->left=NULL;
p1->right=NULL;
//constructing the 3rd node
struct Node * p2;
p2=(struct Node *)malloc(sizeof(struct Node));
p2->data=4;
p2->left=NULL;
p2->right=NULL;
*/
111
// 5
// / \
// 3 6
// / \
// 1 4
//linking root with left and right child
p->left=p1;
p->right=p2;
//linking left child with its left and right child
p1->left=p3;
p1->right=p4;
//linking right child with its left and right child
p2->left=NULL;
p2->right=NULL;
//
p3->left=NULL;
p3->right=NULL;
//
p4->left=NULL;
p4->right=NULL;
Output:
112
Assignments:-
Viva Questions:-
1. What is a tree?
2. What is a binary tree?
3. Define path, degree of a tree and forest?
4. What is a forest tree?
5. What is a binary search tree?
113
EXPERIMENT No. 17
Aim:- Write a program for traversal of graph (B.F.S., D.F.S.).
17.1 BFS:
Theory:-
114
Source Code:-
#include<stdio.h>
#include<conio.h>
#define SIZE 10
#define FALSE 0
#define TRUE 1
115
}
}
for(k=1;k<=G->nodes;k++)
{
if ( !G->visited[k] )
{
add_queue(q,k);
do
{
k= delete_queue(q);
G->visited[k] = TRUE;
for(j=1;j<=G->nodes;j++)
{
if(G->mat[k][j] == 0)
continue;
if (!G->visited[j])
{
G->visited[j] = TRUE;
add_queue(q, j);
}
}
}while(front!=rear);
}
}
printf(“\n Adjacency matrix of a graph is :\n”);
for(i=1;i<=G->nodes;i++)
{
for(k=1;k<=G->nodes;k++)
{
printf(“%d\t”,G->mat[i][k]);
}
printf(“\n”);
}
i=0;
printf(“\n Traversal of a given graph is \n”);
while(i<G->nodes)
{
printf(“%d\t”,q[++i]);
}
}
/********** Function Definition ends **********/
116
}
/********** Function Definition ends **********/
Output:
117
Enter data of vertex 1 for (3,4) :
Enter 1 for adjacent vertex and 0 for otherwise : 0
Assignments:-
Viva Questions:-
118
17.2 DFS:
Theory:-
119
Source Code:-
#include<stdio.h>
#include<conio.h>
#define SIZE 10
#define FALSE 0
#define TRUE 1
typedef int adj_mat[SIZE][SIZE];
typedef struct graph_t{
int nodes[SIZE];
int n;
int *visited;
adj_mat mat;
}graph;
120
{
if ( !G->visited[k] )
visit(G, k);
}
printf(“\n Adjacency matrix of the grpah is \n”);
for(i=1;i<=G->n;i++)
{
for(k=1;k<=G->n;k++)
{
printf(“%d\t”,G->mat[i][k]);
}
printf(“\n”);
}
i=0;
printf(“\n Traversal of a given graph is \n”);
while(i<G->n)
{
printf(“%d\t”,G->nodes[++i]);
}
}
/********** Function Definition ends **********/
/********** visiting graph **********/
/********** Function Definition begins **********/
void visit( graph *G, int k )
{
int j;
G->visited[k] = TRUE;
G->nodes[++find] = k;
for(j=1;j<=G->n;j++)
{
if(G->mat[k][j] == 1)
{
if (!G->visited[j])
visit( G, j );
}
}
}
/********** Function Definition ends **********/
Output:
121
Enter data of vertex 1 for (1,2) :
Enter 1 for adjacent vertex and 0 for otherwise : 1
Assignments:-
Viva Questions:-
122