0% found this document useful (0 votes)
35 views97 pages

Kuldeep D Slab

...

Uploaded by

vk studio
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
35 views97 pages

Kuldeep D Slab

...

Uploaded by

vk studio
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 97

Name: KULDEEP NARAYAN MINJ

Roll: 17115037

--------Menu-----------
1.Traverse
2.Insert
3.Delete
4.Exit
-----------------------
Enter your choice: 2

Enter the position for the new element: 0

Enter the element to be inserted : 10

--------Menu-----------
1.Traverse
2.Insert
3.Delete
4.Exit
-----------------------
Enter your choice: 2

Enter the position for the new element: 1

Enter the element to be inserted : 20

--------Menu-----------
1.Traverse
2.Insert
3.Delete
4.Exit
-----------------------
Enter your choice: 2

Enter the position for the new element: 2

Enter the element to be inserted : 30


Experiment-1
Aim- Write a program to perform traversal, insertion and deletion
in an array.
Theory: Array, is a data structure consisting of a collection of
elements (values or variables), each identified by at least
one array index or key. An array is stored such that the position of
each element can be computed from its index tuple by a
mathematical formula.The simplest type of data structure is a linear
array, also called one-dimensional array.

Applications: Arrays are used to Store List of values.Arrays are used


to Perform Matrix Operations. Arrays are used to implement Search
Algorithms. Arrays are used to implement Sorting Algorithms.
Program Code-
Name: KULDEEP NARAYAN MINJ
Roll: 17115037

#include<stdio.h>
int a[20],b[20],c[40];
int m,n,p,val,i,j,key,pos,temp;
void traverse();
void insert();
void del();

int main()
{
int choice;
do{
printf("\n\n--------Menu-----------\n");
printf("1.Traverse\n");
printf("2.Insert\n");
printf("3.Delete\n");
printf("4.Exit\n");
printf("-----------------------");
printf("\nEnter your choice:\t");
scanf("%d",&choice);
switch(choice)
{

case 1:
Name: KULDEEP NARAYAN MINJ
Roll: 17115037
--------Menu--------
1.Traverse
2.Insert
3.Delete
4.Exit
-----------------------
Enter your choice: 1

The array elements are:


10 20 30

--------Menu-----------
1.Traverse
2.Insert
3.Delete
4.Exit
-----------------------
Enter your choice: 3

Enter the position of the element to be deleted: 1

The deleted element is =20

--------Menu-----------
1.Traverse
2.Insert
3.Delete
4.Exit
-----------------------
Enter your choice: 1

The array elements are:


10 30

--------Menu-----------
1.Traverse
2.Insert
3.Delete
4.Exit
-----------------------
Enter your choice: 4
Program aborted!
Process returned 0 (0x0) execution time : 36.984 s
traverse();
break;
case 2:
insert();
break;
case 3:
del();
break;
case 4:
printf("rogram aborted!");
break;
default:
printf("\nInvalid choice:\n");
break;
}
}while(choice!=4);
return 0;
}
void traverse()
{
int i;
printf("\nThe array elements are:\n");
for(i=0;i<n;i++){
printf("%d\t",a[i]);
}
}
void insert()
{
printf("\nEnter the position for the new element:\t");
scanf("%d",&pos);
printf("\nEnter the element to be inserted :\t");
scanf("%d",&val);
for(i=n-1;i>=pos;i--)
{
a[i+1]=a[i];
}
a[pos]=val;
n=n+1;
}
void del()
{
printf("\nEnter the position of the element to be deleted:\t");
scanf("%d",&pos);
val=a[pos];
for(i=pos;i<n-1;i++)
{
a[i]=a[i+1];
}
n=n-1;
printf("\nThe deleted element is =%d",val);

}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037

Enter number of elements in array


10
Enter 10 integer(s)
2 44 56 28 37 41 9 8 2 24
Enter a number to search
9
9 is present at location 7.

Process returned 0 (0x0) execution time : 30.323 s


Press ENTER to continue.

Enter number of elements in array


10
Enter 10 integer(s)
2 44 56 28 37 41 9 8 2 24
Enter a number to search
3
3 isn't present in the array.

Process returned 0 (0x0) execution time : 18.826 s


Press ENTER to continue.
Experiment-3
Aim- Write a program to implement linear search in an array.

Theory: Linear search (Searching algorithm) is used to find whether


a given number is present in an array and if it is present then at what
location it occurs. It is also known as sequential search. It is
straightforward and works as follows: We keep on comparing each
element with the element to search until it is found or the list ends.

Applications: Linear search is usually very simple to implement, and


is practical when the list has only a few elements, or when
performing a single search in an unordered list. When many values
have to be searched in the same list, it often pays to pre-process the
list in order to use a faster method. For example, one may sort the
list and use binary search, or build an efficient search data structure
from it. Should the content of the list change frequently, repeated
re-organization may be more trouble than it is worth.
Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include <stdio.h>
int main()
{
int array[100], search, c, n;

printf("Enter number of elements in array\n");


scanf("%d", &n);

printf("Enter %d integer(s)\n", n);

for (c = 0; c < n; c++)


scanf("%d", &array[c]);

printf("Enter a number to search\n");


scanf("%d", &search);

for (c = 0; c < n; c++)


{if (array[c] == search) /* If required element is found */ {
printf("%d is present at location %d.\n", search, c+1);
break;
}
}
if (c == n)
printf("%d isn't present in the array.\n", search);

return 0;
}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
Enter number of elements
10
Enter 10 integers
2 4 6 8 9 12 14 20 33 36
Enter value to find
6
6 found at location 3.

Process returned 0 (0x0) execution time : 80.969 s


Press ENTER to continue.

Enter number of elements


10
Enter 10 integers
2 4 6 8 9 12 14 20 33 36
Enter value to find
3
Not found! 3 isn't present in the list.

Process returned 0 (0x0) execution time : 8.854 s


Press ENTER to continue
Experiment-4
Aim- Write a program to implement binary search in an array.

Theory: Binary Search can only be used for sorted arrays, but it's
fast as compared to linear search. If you wish to use binary search
on an array which isn't sorted, then you must sort it using some
sorting technique say merge sort and then use the binary search
algorithm to find the desired element in the list. If the element to be
searched is found then its position is printed.
Applications:
Swift implementation
Searching for prefixes
Autocompletion
Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include <stdio.h>
int main()
{
int c, first, last, middle, n, search, array[100];

printf("Enter number of elements\n");


scanf("%d",&n);

printf("Enter %d integers\n", n);

for (c = 0; c < n; c++)


scanf("%d",&array[c]);

printf("Enter value to find\n");


scanf("%d", &search);

first = 0;
last = n - 1;
middle = (first+last)/2;
while (first <= last
) if (array[middle] < search)

first = middle + 1;
else if (array[middle] == search) {
printf("%d found at location %d.\n", search,
middle+1); break;
}
Else

last = middle - 1;

middle = (first + last)/2;


}
if (first > last)
printf("Not found! %d isn't present in the list.\n", search);

return 0;}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
Enter size of array:4

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:1

Enter element:20
Operation successful.

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:1

Enter element:3
Operation successful.

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:1

Enter element:45
Operation successful.

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:1

Enter element:55
Operation successful.

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:1
OVERFLOW!
Experiment-8
Aim- Write a program to implement stack and perform push and
pop operation.

Theory: A stack is a basic data structure that can be logically thought


of as a linear structure represented by a real physical stack or pile, a
structure where insertion and deletion of items takes place at one
end called top of the stack. The basic concept can be illustrated by
thinking of your data set as a stack of plates or books where you can
only take the top item off the stack in order to remove things from it.

Applications: Expression Evaluation: Stack is used to evaluate prefix,


postfix and infix expressions.

Expression Conversion: An expression can be represented in prefix,


postfix or infix notation. Stack can be used to convert one form of
expression to another.

Syntax Parsing: Many compilers use a stack for parsing the syntax of
expressions, program blocks etc. before translating into low level
code.

Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include <stdio.h>
int a[100],top,c,n;

void push()
{
if(top==n)
{
printf("OVERFLOW!\n");
}else
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:3
Stack arrangement is displayed below.
55
45
3
20
Operation successful.

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:2
Popped element is 0.
Operation successful.

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:2
Popped element is 55.
Operation successful.

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:3
Stack arrangement is displayed below.
3
20
Operation successful.

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:2
Popped element is 45.
Operation successful.
{
printf("\nEnter element:");
scanf("%d",&a[top]);
top++;
printf("Operation successful.\n");
}
}

void pop()
{
if(top==0)
{
printf("UNDERFLOW!\n");
}
else
{
printf("Popped element is %d.",a[top]);
printf("\nOperation successful.\n");
top--;
}
}
void display()
{
int i=top-1;
printf("Stack arrangement is displayed
below.\n"); for(;i>=0;i--)
{
printf("\t%d\n",a[i]);
}
printf("Operation successful.\n");
}

int main()
{
printf("Enter size of array:");
scanf("%d",&n);
do
{
printf("\n1.Push\n2.Pop\n3.Display\n4.Exit\nEnter operation
detail:"); scanf("%d",&c);
switch(c)
{
case 1: push(); break;
case 2: pop(); break;
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:2
Popped element is 3.
Operation successful.

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:2
UNDERFLOW!

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:3
Stack arrangement is displayed below.
Operation successful.

1.Push
2.Pop
3.Display
4.Exit
Enter operation detail:4

Process returned 0 (0x0) execution time : 50.585 s


Press ENTER to continue.
case 3: display(); break;
case 4: break ;
default :printf("Invalid Input.\n");
}
}while(c!=4);
return 0;
}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037

123
046
004

Check
1. Upper
2. Lower
3. Tridiagonal
4. Exit

1
Upper triangular!

Check
1. Upper
2. Lower
3. Tridiagonal
4. Exit

2
Not Lower triangular!

Check
1. Upper
2. Lower
3. Tridiagonal
4. Exit

4
Program aborted!
Process returned 0 (0x0) execution time : 19.907 s
Press any key to continue.
Experiment-7
Aim- Write a program to check whether input matrix is
upper triangular, lower triangular or tridiagonal matrix.

Theory: A square matrix is called lower triangular if all the entries


above the main diagonal are zero. Similarly, a square matrix is called
upper triangular if all the entries below the main diagonal are zero.
A tridiagonal matrix is a band matrix that has nonzero elements only
on the main diagonal, the first diagonal below this, and the first
diagonal above the main diagonal.
Applications: Storage: There are lesser non-zero elements than zeros
and thus lesser memory can be used to store only those elements.

Computing time: Computing time can be saved by logically designing


a data structure traversing only non-zero elements..
Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include<stdio.h>
int arr[3][3];
void upper();
void lower();
void tridiagonal();
void upper()
{ int c,flg=0,i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
if(i>j)
{
if(arr[i][j]==0)
c+=1;
else
flg+=1;
}

}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
120
456
038

Check
1. Upper
2. Lower
3. Tridiagonal
4. Exit

3
Tridiagonal!

Check
1. Upper
2. Lower
3. Tridiagonal
4. Exit

2
Not Lower triangular!

Check
1. Upper
2. Lower
3. Tridiagonal
4. Exit

4
Program aborted!
Process returned 0 (0x0) execution time : 21.502 s
Press any key to continue.
}
if(flg==0)
printf("Upper triangular!");
else
printf("Not Upper triangular!");
}

void lower()
{ int c,flg=0,i,j;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{ if(i<j)
{
if(arr[i][j]==0)
c+=1;
else
flg+=1;
}

}
}
if(flg==0)
printf("Lower triangular!");
else
printf("Not Lower triangular!");
}

void tridiagonal()
{ inti,j,c=0,flg=0;
for(i=0;i<3;i++)
{ for(j=0;j<3;j++)
if (i-j==1 || j-i==1 || i-j==0)
c+=1;
else
{
if(arr[i][j]!=0)
flg+=1;
}
}
if(flg==0)
printf("Tridiagonal!");
else
printf("Non Tridiagonal!");
}
int main()
{

int i,j,ch;
for(i=0;i<3;i++)
{
for(j=0;j<3;j++)
{
scanf("%d",&arr[i][j]);

}
}
ch=0;

while(ch!=4)
{ printf("\n\nCheck\n1. Upper\n2. Lower\n3. Tridiagonal\n4. Exit\n\n");
scanf("%d",&ch);
if(ch==1)
upper();
else
if(ch==2) lower();
else if(ch==3)
tridiagonal();
else if(ch==4)
printf("Program aborted!");
else
printf("Enter valid choice.\n");
}
return 0;
}
abcd^e-fgh*+^*+i-
Process returned 0 (0x0) execution time : 0.001 s
Press ENTER to continue.
Experiment-10
Aim- Write a program to convert infix expression to
postfix expression.
Theory:
Infix Notation

We write expression in infix notation, e.g. a - b + c, where operators


are used in-between operands. It is easy for us humans to read,
write, and speak in infix notation but the same does not go well with
computing devices. An algorithm to process infix notation could be
difficult and costly in terms of time and space consumption.
Prefix Notation

In this notation, operator is prefixed to operands, i.e. operator is


written ahead of operands. For example, +ab. This is equivalent to its
infix notation a + b. Prefix notation is also known as Polish Notation.
Postfix Notation

This notation style is known as Reversed Polish Notation. In this


notation style, the operator is postfixed to the operands i.e., the
operator is written after the operands. For example, ab+. This is
equivalent to its infix notation a + b.
Applications:
Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

struct Stack
{
int top;
unsigned capacity;
int* array;

};
struct Stack* createStack( unsigned capacity )
{
struct Stack* stack = (struct Stack*) malloc(sizeof(struct Stack));

if (!stack)
return NULL;

stack->top = -1;

stack->capacity = capacity;

stack->array = (int*) malloc(stack->capacity * sizeof(int));

if (!stack->array)
return NULL;
return stack;
}
int isEmpty(struct Stack* stack)
{
return stack->top == -1 ;
}
char peek(struct Stack* stack)
{
return stack->array[stack->top];
}
char pop(struct Stack* stack)
{
if (!isEmpty(stack))
return stack->array[stack->top--] ;
return '$';
}
void push(struct Stack* stack, char op)
{
stack->array[++stack->top] = op;
}

int isOperand(char ch)


{
return (ch>= 'a' &&ch<= 'z') || (ch>= 'A' &&ch<= 'Z');
}

int Prec(char ch)


{
switch (ch)
{
case '+':
case '-':
return 1;

case '*':
case '/':
return 2;

case '^':
return 3;
}
return -1;
}

int infixToPostfix(char* exp)


{
int i, k;

struct Stack* stack = createStack(strlen(exp));


if(!stack) // See if stack was created successfully
return -1 ;

for (i = 0, k = -1; exp[i]; ++i)


{
if (isOperand(exp[i]))
exp[++k] = exp[i];

else if (exp[i] == '(')


push(stack, exp[i]);

else if (exp[i] == ')')


{
while (!isEmpty(stack) && peek(stack) != '(')
exp[++k] = pop(stack);
if (!isEmpty(stack) && peek(stack) != '(')
return -1; // invalid expression
else
pop(stack);
}
else // an operator is encountered
{
while (!isEmpty(stack) &&Prec(exp[i]) <= Prec(peek(stack)))
exp[++k] = pop(stack);
push(stack, exp[i]);
}

}
while (!isEmpty(stack))
exp[++k] = pop(stack );

exp[++k] = '\0';
printf( "%s", exp );
}

int main()
{
char exp[] = "a+b*(c^d-e)^(f+g*h)-i";
infixToPostfix(exp);
return 0;
}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037

1.Addition
2. Deletion
3. Display
4. Exit
1
23
1.Addition
2. Deletion
3. Display
4. Exit
1
24
1.Addition
2. Deletion
3. Display
4. Exit
1
25
1.Addition
2. Deletion
3. Display
4. Exit
3
23,24,25,
1.Addition
2. Deletion
3. Display
4. Exit
1
26
1.Addition
2. Deletion
3. Display
4. Exit
3
23,24,25,26,
Experiment-13
Aim- Write a program to implement insertion and deletion in a
linear queue.

Theory: A queue is a data structure that is somewhat like a stack,


except that in a queue the first item inserted is the first to be
removed (First-In-First-Out, FIFO), while in a stack, as we've seen,
the last item inserted is the first to be removed (LIFO). A queue
works like the line you wait in. The queue abstract data type defines
a collection that keeps objects in a sequence, where: - element
access and deletion are restricted to the first element in the
sequence, which is called the front of the queue, and - element
insertion is restricted to the end of the sequence, which is called the
rear of the queue. In a linear queue, the traversal through the queue
is possible only once, i.e., once an element is deleted, we cannot
insert another element in its position.

Applications: Queue is used when things don’t have to be


processed immediately, but have to be processed in First In First
Out order like Breadth First Search. This property of Queue makes it
also useful in following kind of scenarios:

1) When a resource is shared among multiple consumers.


Examples include CPU scheduling, Disk Scheduling.

2) When data is transferred asynchronously (data not necessarily


received at same rate as sent) between two processes. Examples
include IO Buffers, pipes, file IO, etc.
Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include <stdio.h>
int a[5];
int f,r;

void addition()
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
1.Addition
2. Deletion
3. Display
4. Exit
2
1.Addition
2. Deletion
3. Display
4. Exit
3
24,25,26,
1.Addition
2. Deletion
3. Display
4. Exit
2
1.Addition
2. Deletion
3. Display
4. Exit
3
25,26,
1.Addition
2. Deletion
3. Display
4. Exit
4

Process returned 0 (0x0) execution time : 93.061 s


Press ENTER to continue.
{
if(f==5)
{
printf("OVERFLOW!\n");
}
else
{
scanf("%d",&a[f]);
f++;
}
}

void deletion()
{
if(r==f)
{
printf("UNDERFLOW!\n");
}
else
{
r++;
}
}

void display()
{
int d,b;
d=f-1;
b=r;
for(b=r;b<=d;b++)
{
printf("%d,",a[b]);
}
printf("\n");
}

int main()
{
int c;
do{
printf("1.Addition\n2. Deletion\n3. Display\n4. Exit\n");
scanf("%d",&c);
switch(c)
{
case 1: addition();break;
case 2: deletion();break;
case 3: display();break;
case 4: break;
default: printf("Invalid Input!");
}
}while(c!=4);
}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037

1. Insert
2. Delete
3. Display
4. Exit
Enter the choice: 1

Enter the character item to be inserted: a

1. Insert
2. Delete
3. Display
4. Exit
Enter the choice: 1

Enter the character item to be inserted: s

1. Insert
2. Delete
3. Display
4. Exit
Enter the choice: 1

Enter the character item to be inserted: d

1. Insert
2. Delete
3. Display
4. Exit
Enter the choice: 1

Enter the character item to be inserted: f

1. Insert
2. Delete
3. Display
4. Exit
Enter the choice: 3

Contents of Queue is:


a s d f
Experiment-14
Aim- Write a program to implement insertion and deletion in a
circular queue.

Theory: Circular Queue is also a linear data structure, which follows


the principle of FIFO(First In First Out), but instead of ending the
queue at the last position, it again starts from the first position after
the last, hence making the queue behave like a circular data
structure. Circular Queue works by the process of circular increment
i.e. when we try to increment any variable and we reach the end of
queue, we start from the beginning of queue by modulo division with
the queue size.

Applications: Some common real-world examples where circular


queues are used:

Computer controlled Traffic Signal System uses circular


queue. CPU scheduling and Memory management. Program
Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include<stdio.h>
#include<stdlib.h>
#define MAX 4

int ch, front = 0, rear = -1, count=0;


char q[MAX],item;

void insert()
{
if(count == MAX)
printf("\nQueue is Full");

else
{
rear = (rear + 1) % MAX;
q[rear]=item;
count++;
}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
1. Insert
2. Delete
3. Display
4. Exit
Enter the choice: 2

Deleted item is: a


1. Insert
2. Delete
3. Display
4. Exit
Enter the choice: 2

Deleted item is: s


1. Insert
2. Delete
3. Display
4. Exit
Enter the choice: 3

Contents of Queue is:


d f
}
void del()

{
if(count == 0)
printf("\nQueue is Empty");
else

{
if(front > rear && rear==MAX-1)
{
front=0;
rear=-1;
count=0;
}
else
{

item=q[front];
printf("\nDeleted item is: %c",item);
front = (front + 1) % MAX;
count--;

}
}
}

void display()
{
int i, f=front, r=rear;
if(count == 0)
printf("\nQueue is Empty");

else
{
printf("\nContents of Queue is:\n");
for(i=f; i<=r; i++)
{

printf("%c\t", q[i]);
f = (f + 1) % MAX;
}
}
}

int main()
{
while(1)
{
printf("\n1. Insert\n2. Delete\n3. Display\n4. Exit");
printf("\nEnter the choice: ");

scanf("%d", &ch);
switch(ch)
{
case 1:
printf("\nEnter the character item to be inserted: ");
scanf(" %c",&item);
insert();
break;
case 2:
del();
break;
case 3:
display();
break;
case 4:
return 0;
break;

}
}
return 0;
}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:1

Enter number of elements:5

Enter the data:10


23
44
56
76

1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:6

10
23
44
56
76

1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:4

Element deleted is 76
Experiment-16
Aim- Write a program to implement insertion and deletion in a
double-ended queue.

Theory: In computer science, a double-ended queue (abbreviated to


deque) is an abstract data type that generalizes a queue, for which
elements can be added to or removed from either the front (head)
or back (tail). It is also often called a head-tail linked list, though
properly this refers to a specific data structure implementation of a
deque.

Applications: Since Deque supports both stack and queue


operations, it can be used as both. The Deque data structure
supports clockwise and anticlockwise rotations in O(1) time
which can be useful in certain applications.
Also, the problems where elements need to be removed and
or added both ends can be efficiently solved using Deque.
Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include<stdio.h>
#include<process.h>
#define MAX 30

typedef struct dequeue


{
int data[MAX];
int rear,front;
}dequeue;

void initialize(dequeue *p);


int empty(dequeue *p);
int full(dequeue *p);
void enqueueR(dequeue *p,int x);
void enqueueF(dequeue *p,int x);
int dequeueF(dequeue *p);
int dequeueR(dequeue *p);
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:6

10
23
44
56

1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:5

Element deleted is 10

1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:6

23
44
56
void print(dequeue *p);
void main()
{
int i,x,op,n;
dequeue q;

initialize(&q);

do
{

printf("\n1.Create\n2.Insert(rear)\n3.Insert(front)\n4.Delete(rear)\n5.Delete(front)"
);
printf("\n6.Print\n7.Exit\n\nEnter your
choice:"); scanf("%d",&op);

switch(op)
{
case 1: printf("\nEnter number of elements:");
scanf("%d",&n);
initialize(&q);
printf("\nEnter the data:");

for(i=0;i<n;i++)
{
scanf("%d",&x);
if(full(&q))
{
printf("\nQueue is full!!");
exit(0);
}
enqueueR(&q,x);
}
break;

case 2: printf("\nEnter element to be


inserted:"); scanf("%d",&x);

if(full(&q))
{
printf("\nQueue is full!!");
exit(0);
}

enqueueR(&q,x);
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037

1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:2

Enter element to be inserted:77

1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:6

23
44
56
77

1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:3

Enter the element to be inserted:99


break;

case 3: printf("\nEnter the element to be


inserted:"); scanf("%d",&x);

if(full(&q))
{
printf("\nQueue is full!!");
exit(0);
}

enqueueF(&q,x);
break;

case 4: if(empty(&q))
{
printf("\nQueue is empty!!");
exit(0);
}

x=dequeueR(&q);
printf("\nElement deleted is %d\n",x);
break;

case 5: if(empty(&q))
{
printf("\nQueue is empty!!");
exit(0);
}

x=dequeueF(&q);
printf("\nElement deleted is %d\n",x);
break;

case 6: print(&q);
break;

default: break;
}
}while(op!=7);
}

void initialize(dequeue *P)


{
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:6

99
23
44
56
77

1.Create
2.Insert(rear)
3.Insert(front)
4.Delete(rear)
5.Delete(front)
6.Print
7.Exit

Enter your choice:7

Process returned 7 (0x7) execution time : 481.118 s


Press any key to continue.
P->rear=-1;
P->front=-1;
}

int empty(dequeue *P)


{
if(P->rear==-1)
return(1);

return(0);
}

int full(dequeue *P)


{
if((P->rear+1)%MAX==P->front)
return(1);

return(0);
}

void enqueueR(dequeue *P,int x)


{
if(empty(P))
{
P->rear=0;
P->front=0;
P->data[0]=x;
}
else
{
P->rear=(P->rear+1)%MAX;
P->data[P->rear]=x;
}
}

void enqueueF(dequeue *P,int x)


{
if(empty(P))
{
P->rear=0;
P->front=0;
P->data[0]=x;
}
Else
{
P->front=(P->front-1+MAX)%MAX;
P->data[P->front]=x;
}
}

int dequeueF(dequeue *P)


{
int x;

x=P->data[P->front];

if(P->rear==P->front) //delete the last element


initialize(P);
else
P->front=(P->front+1)%MAX;

return(x);
}

int dequeueR(dequeue *P)


{
int x;

x=P->data[P->rear];

if(P->rear==P->front)
initialize(P);
else
P->rear=(P->rear-1+MAX)%MAX;

return(x);
}

void print(dequeue *P)


{
if(empty(P))
{
printf("\nQueue is empty!!");
exit(0);
}

int i;
i=P->front;
while(i!=P->rear)
{
printf("\n%d",P->data[i]);
i=(i+1)%MAX;
}

printf("\n%d\n",P->data[P->rear]);
}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
Key 50 inserted

Key 80 inserted

Key 30 inserted

Key 40 inserted

Key 20 inserted

Key 100 inserted

Key 50 found

No key found for value - 10.

Successfully deleted node. Now tree root node is - 80.

No key found for value - 50.

Preorder Traversal: 80 30 20 40 100

Inorder Traversal: 20 30 40 80 100

Postorder Traversal: 20 40 30 100 80


Experiment-
Aim- Write a program to create a binary search tree and
perform insertion, deletion and traversal.

Theory: In computer science, binary search trees (BST), sometimes


called ordered or sorted binary trees, are a particular type of
container: data structures that store "items" (such as numbers,
names etc.) in memory. They allow fast lookup, addition and
removal of items, and can be used to implement either dynamic sets
of items, or lookup tables that allow finding an item by its key (e.g.,
finding the phone number of a person by name).
Applications: 1) Used to express arithmetic expressions
2) Used to evaluate expression trees.
3) Used for managing virtual memory Areas (VMA's)
4) Used for indexing IP addresses.

5) Hashing would be faster, but want to avoid attacker sending


IP packets with worst-case inputs.
6) For dynamic sorting.
Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include<stdio.h>

#include<stdlib.h>

typedef struct node{

int key;

struct node *left;

struct node *right;

}Node;

Node * newNode(int key){


Node *temp = (Node *)malloc(sizeof(Node));

temp->key = key;

temp->left = NULL;

temp->right = NULL;

return temp;

/*for inserting the key, newNode is the node needed to be inserted */


Node * insert(Node *p, Node *nwNode){

if(!p){

printf("Key %d\tinserted\n", nwNode->key);

return nwNode;

if(nwNode->key > p->key){

insert(p->right, nwNode);

if(!(p->right))

p->right = nwNode;

else{

insert(p->left, nwNode);

if(!(p->left))

p->left = nwNode;

return p;

/* for searching the key */


void search(Node *p, int searchKey){

if(!p){

printf("No key found for value - %d.\n", searchKey);


return ;

if(p->key == searchKey){

printf("Key %d\tfound\n", searchKey);

else if(p->key <searchKey)

search(p->right, searchKey);

else

search(p->left, searchKey);

/* inorder successor in BST will be the minimum key in right subtree


*/ Node * getInSuccessor(Node *p){

while(p->left != NULL)

p = p->left; //this will give the minimum key

return p;

Node * deletion(Node *p, int delKey){

struct node *temp;


if(!p){

printf("Unable to delete. No such key exists.\n");

return p;

else if(delKey> p->key)

p->right = deletion(p->right, delKey);

else if(delKey< p->key)

p->left = deletion(p->left, delKey);

/* executing else means get the key */

else{

/* node has one child or no child */

if(p->left == NULL){

temp = p->right;

free(p);

return temp;

else if(p->right == NULL){

temp = p->left;

free(p);

return temp;

/* node with two children, interchange with inorder successor */

temp = getInSuccessor(p->right);

p->key = temp->key;

p->right = deletion(p->right, temp->key); // Delete the inorder successor

return p;

}
void traversePreorder(Node *p){

if(!p)

return ;

printf("%d ", p->key);

traversePreorder(p->left);

traversePreorder(p->right);

/* Inorder traversal that outputs key in non-decreasing order*/


void traverseInorder(Node *p){

if(!p)

return ;

traverseInorder(p->left);

printf("%d ", p->key);

traverseInorder(p->right);

/* Postorder traversal that outputs key in non-decreasing order*/


void traversePostorder(Node *p){

if(!p)

return ;

traversePostorder(p->left);

traversePostorder(p->right);

printf("%d ", p->key);


}

int main(void){

Node *root = NULL;

root = insert(root, newNode(50));

insert(root, newNode(80));

insert(root, newNode(30));

insert(root, newNode(40));

insert(root, newNode(20));

insert(root, newNode(100));

search(root, 50);

search(root, 10);

Node *newRoot = deletion(root, 50);

if(newRoot){

printf("Successfully deleted node. Now tree root node is - %d.\n", newRoot->key);

search(root, 50);

printf("Preorder Traversal: ");

traversePreorder(root);

printf("\nInorder Traversal: ");

traverseInorder(root);

printf("\nPostorder Traversal: ");

traversePostorder(root);

return 0;

}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037

Enter the size of the list : 5


Enter Element 1 : 3
Enter Element 2 : 1
Enter Element 3 : 5
Enter Element 4 : 4
Enter Element 5 : 2
Numbers Entered : 3, 1, 5, 4, 2
Menu:
1 . Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Exit
Your Choice : 1
Sorted List in ascending order : 1, 2, 3, 4, 5
Do you want to continue( press 1 to continue any other number to exit) : 1
Menu:
1 . Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Exit
Your Choice : 2
Sorted List in ascending order : 1, 2, 3, 4, 5
Do you want to continue( press 1 to continue any other number to exit) : 1
Menu:
1 . Bubble Sort
2. Selection Sort
3. Insertion Sort
4. Exit
Your Choice : 3
Sorted List in ascending order : 1, 2, 3, 4, 5
Do you want to continue( press 1 to continue any other number to exit) : 1
Experiment
Aim- Write a program to implement bubble sort, selection
sort, insertion sort.
Theory:

Bubble Sort - It is a sorting algorithm in which two adjacent elements


of an array are checked and swapped if they are in wrong order and
this process is repeated until we get a sorted array.

In this first two elements of the array are checked and swapped if
they are in wrong order. Then first and third elements are
checked and swapped if they are in wrong order. This continues
till the lat element is checked and swapped if necessary.

Selection Sort - It is also a sorting algorithm in which first step is to


find the smallest element in the array. This smallest element is
swapped with the first element. After this, search for the smallest
element in the subarray formed by excluding the first element
and compare it with the first element of the subarray. Repeat it
till the array gets sorted.

Insertion Sort - In this, the second element is compared with the first
element and is swapped if it is not in order. Similarly, we take the
third element in the next iteration and place it at the right place in
the subarray of the first and second elements (as the subarray
containing the first and second elements is already sorted). We
repeat this step with the fourth element of the array in the next
iteration and place it at the right position in the subarray containing
the first, second and the third elements. We repeat this process until
our array gets sorted.
Applications:
Bubble Sort: Bubble sort is used in programming TV remote to
sort channels on the basis of longer viewing time..
Insertion sort: Offers low constant factors and is good for sorting
small lists, also appears as base cases to mergesort and quicksort
when the size of a subcase gets small.

Selection sort has a quite important application because each item is


actually moved at most once, Section sort is a method of choice for
sorting files with very large objects (records) and small keys.
Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include <stdio.h>
#include<stdlib.h>

void bubble(int *,int);


void selection(int *,int);
void insertion(int *,int);

int main()
{
int count=0;
int choice=0,ch=0;
int check=0;
int i=0;
printf("Enter the size of the list: ");
scanf("%d",&count);
int list[count];

for(i=0;i<count;i++)
{
printf("Enter element %d: ",i+1);
scanf("%d",&list[i]);
}

printf("\nNumbers entered: ");


for(i=0;i<count;i++)
printf("%d,",list[i]);
printf("\n");

do{
printf("Menu:\n\n");
printf("1.Bubble sort\n2.Selection Sort\n3.Inserton sort\n4.Exit\nYour choice: ");
scanf("%d",&choice);

switch(choice)
void print(dequeue *p);
case 1: //performs bubble sort
bubble(list,count);
break;

case 2: //performs selection sort


selection(list,count);
break;

case 3: //performs insertion sort


insertion(list,count);
break;

case 4: return 0;

default: printf("Invalid option\nRetry: ");


break;

}
printf("Do you want to continue(press 1 to continue any other number to exit): ");
scanf("%d",&ch);
} while(ch==1);

return 0;
}
void bubble(int *list,int n)
{
int i,j;
int c;
for(i=0;i<n;i++)
{
for (j=0;j<n-i-1;j++)
{
if (list[j] > list[j+1])
{
c=list[j];
list[j]=list[j+1];
list[j+1]=c;
}
}
}

printf("\nSorted list in ascending order:\n");


for ( i = 0 ; i< n ; i++ )
printf("%d,",list[i]);
printf("\n");
}
void selection(int *list,int n){
int i;
int j,min;
int k;
for(j=0;j<n-1;j++)
{

min=list[j];
k=j;
for(i=j+1;i<n;i++)
{

if(list[i]<min)
{
min=list[i];
k=i;
}

list[k]=list[j];
list[j]=min;

}
printf("Sorted list is:");
for(i=0;i<n;i++)
{
printf("%d,",list[i]);
}
printf("\n");
}
void insertion(int *list,int n)
{
int temp;
int i=0,j=0;

for(i=1;i<n;i++)
{
temp=list[i];
j=i-1;
while((j>=0)&&(list[j]>temp))
{
list[j+1]=list[j];
j--;
}
list[j+1]=temp;
}
printf("Sorted list is: ");
for(i=0;i<n;i++)
{
printf("%d,",list[i]);
}

printf("\n");
}
Name: KULDEEP NARAYAN MINJ
Roll: 17115037

Enter no of elements :6

Enter the nos : 33 4 11 54 6 2


Heap array : 54 33 11 4 6 2
The sorted array is : 2 4 6 11 33 54
Complexity :
Best case = Avg case = Worst case = O(n logn)

Process returned 0 (0x0) execution time : 16.649 s


Press any key to continue.
Experiment
Aim- Write a program to implement heap sort.

Theory: Heapsort is a comparison-based sorting algorithm.


Heapsort can be thought of as an improved selection sort: like that
algorithm, it divides its input into a sorted and an unsorted region,
and it iteratively shrinks the unsorted region by extracting the
largest element and moving that to the sorted region. The
improvement consists of the use of a heap data structure rather
than a linear-time search to find the maximum.

Applications: Heapsort is great when you need to know just the


"smallest" (or "largest") of a collection of items, without the
overhead of keeping the remaining items in sorted order. For
example, a Priority Queue.

It is used to quickly find the smallest and largest element from


a collection of items or array.
Comparing with Quick Sort, it has better worst case O( nlog(n) ).
Quick Sort has complexity of O(n^2).
Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include <stdio.h>

void main()

int heap[10], no, i, j, c, root, temp;

printf("\n Enter no of elements :");

scanf("%d", &no);

printf("\n Enter the nos : ");

for (i = 0; i< no; i++)

scanf("%d",
&heap[i]);
for(i=0;i<no;i++)

c = i;

do

root = (c - 1) / 2;

if (heap[root] < heap[c]) /* to create MAX heap array */

temp = heap[root];

heap[root] = heap[c];

heap[c] = temp;

c = root;

} while (c != 0);

printf("Heap array : ");

for (i = 0; i< no; i++)

printf("%d\t ", heap[i]);

for (j = no - 1; j >= 0; j--)

temp = heap[0];

heap[0] = heap[j]; /* swap max element with rightmost leaf element */


heap[j] = temp;

root = 0;

do

c = 2 * root + 1; /* left node of root element */

if ((heap[c] <heap[c + 1]) && c < j-1)

c++;

if (heap[root]<heap[c] && c<j) /* again rearrange to max heap array */

{
temp = heap[root];

heap[root] = heap[c];

heap[c] = temp;

root = c;

} while (c < j);

printf("\n The sorted array is : ");

for (i = 0; i< no; i++)

printf("\t %d", heap[i]);

printf("\n Complexity : \n Best case = Avg case = Worst case = O(n logn) \n");

}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
How many elements?6

Enter array elements:33 4 11 54 6 2

Array after sorting:2 4 6 11 33 54


Process returned 0 (0x0) execution time : 20.929 s
Press any key to continue.
Experiment
Aim- Write a program to implement quick sort.

Theory: Quicksort is a comparison sort, meaning that it can sort


items of any type for which a "less-than" relation (formally, a total
order) is defined. In efficient implementations it is not a stable sort,
meaning that the relative order of equal sort items is not preserved.
Quicksort can operate in-place on an array, requiring small additional
amounts of memory to perform the sorting. It is very similar to
selection sort, except that it does not always choose worst-case
partition.

Applications: Quicksort is one of the fastest sorting algorithms, so it


is commonly used in commercial applications. It also has some usage
in graphic/game development where u need to sort data points and
cluster them out.

Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include <stdio.h>

void quick_sort(int[],int,int);
int partition(int[],int,int);

int main()
{
int a[50],n,i;
printf("How many elements?");
scanf("%d",&n);
printf("\nEnter array elements:");

for(i=0;i<n;i++)
scanf("%d",&a[i]);

quick_sort(a,0,n-1);
printf("\nArray after sorting:");
for(i=0;i<n;i++)
printf("%d ",a[i]);
return 0;
}

void quick_sort(int a[],int l,int u)


{
int j;
if(l<u)
{
j=partition(a,l,u);
quick_sort(a,l,j-1);
quick_sort(a,j+1,u);
}
}

int partition(int a[],int l,int u)


{
int v,i,j,temp;
v=a[l];
i=l;
j=u+1;

do
{
do
i++;

while(a[i]<v&&i<=u);
do
j--;
while(v<a[j]);

if(i<j)
{
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}while(i<j);

a[l]=a[j];
a[j]=v;

return(j);
}
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
Simple Merge Sort Example - Functions and Array

Enter 5 Elements for Sorting


33 4 11 54 6

Your Data : 33 4 11 54 6

Sorted Data : 4 6 11 33 54
Process returned 0 (0x0) execution time : 10.737 s
Press any key to continue.
Experiment
Aim- Write a program to implement merge sort.

Theory: Merge sort is a sorting technique based on divide and


conquer technique. With worst-case time complexity being Ο(n
log n), it is one of the most respected algorithms.
Merge sort first divides the array into equal halves and
then combines them in a sorted manner.
Applications: Merge sort is used mostly under size constraints
because it isn't as hefty an algorithm as Quicksort.
Program Code-
Name: KULDEEP
NARAYAN MINJ
Roll: 17115037
#include<stdio.h>

#include<conio.h>

#define MAX_SIZE 5

void merge_sort(int, int);

void merge_array(int, int, int, int);

int arr_sort[MAX_SIZE];

int main() {

int i;

printf("Simple Merge Sort Example - Functions and Array\n");


printf("\nEnter %d Elements for Sorting\n", MAX_SIZE);

for (i = 0; i< MAX_SIZE; i++)

scanf("%d", &arr_sort[i]);

printf("\nYour Data :");


for (i = 0; i< MAX_SIZE; i++) {
printf("\t%d", arr_sort[i]);

merge_sort(0, MAX_SIZE - 1);

printf("\n\nSorted Data :");

for (i = 0; i< MAX_SIZE; i++) {

printf("\t%d", arr_sort[i]);

getch();

void merge_sort(int i, int j) {

int m;

if (i< j) {

m = (i + j) / 2;

merge_sort(i, m);

merge_sort(m + 1, j);

// Merging two arrays


merge_array(i, m, m + 1, j);

void merge_array(int a, int b, int c, int d) {

int t[50];

int i = a, j = c, k = 0;

while (i<= b && j <= d) {

if (arr_sort[i] <arr_sort[j])
t[k++] = arr_sort[i++];

else

t[k++] = arr_sort[j++];

//collect remaining elements

while (i<= b)

t[k++] = arr_sort[i++];

while (j <= d)

t[k++] = arr_sort[j++];

for (i = a, j = 0; i<= d; i++, j++)

arr_sort[i] = t[j];

You might also like