0% found this document useful (0 votes)
0 views

Ds Lab Final-with Program

Uploaded by

rahul0406r
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

Ds Lab Final-with Program

Uploaded by

rahul0406r
Copyright
© © All Rights Reserved
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 98

PANIMALAR ENGINEERING COLLEGE

(An Autonomous Institution, Affiliated to Anna University, Chennai)

(A CHRISITIAN MINORITY INSTITUTION)

JAI SAKTHI EDUCATIONAL TRUST

Accredited By National Board Of Accreditation (NBA)

Bangalore Trunk Road, Varadharajapuram, Nasarathpettai, Poonamallee, Chennai –


600 123.

DEPARTMENT OF ELECTRONICS AND COMMUNICATION


ENGINEERING

23CS1412-PRINCIPLES OF DATA STRUCTURES


LABORATORY
LAB MANUAL
IV SEMESTER
REGULATIONS 2023
DATA STRUCTURE
Introduction

Data Structure can be defined as the group of data elements which


provides an efficient way of storing and organising data in the computer
so that it can be used efficiently. Some examples of Data Structures are
arrays, Linked List, Stack, Queue, etc.

Data Structures are widely used in almost every aspect of Computer


Science i.e. Operating System, Compiler Design, Artificial intelligence,
Graphics and many more.

Data Structures are the main part of many computer science algorithms
as they enable the programmers to handle the data in an efficient way. It
plays a vital role in enhancing the performance of a software or a program
as the main function of the software is to store and retrieve the user's
data as fast as possible

Basic Terminology

Data structures are the building blocks of any program or the software.
Choosing the appropriate data structure for a program is the most difficult
task for a programmer. Following terminology is used as far as data
structures are concerned

Data: Data can be defined as an elementary value or the collection of


values, for example, student's name and its id are the data about the
student.

Group Items: Data items which have subordinate data items are called
Group item, for example, name of a student can have first name and the
last name.

Record: Record can be defined as the collection of various data items, for
example, if we talk about the student entity, then its name, address,
course and marks can be grouped together to form the record for the
student.

File: A File is a collection of various records of one type of entity, for


example, if there are 60 employees in the class, then there will be 20
records in the related file where each record contains the data about each
employee.

Attribute and Entity: An entity represents the class of certain objects. it


contains various attributes. Each attribute represents the particular
property of that entity.

Field: Field is a single elementary unit of information representing the


attribute of an entity.

Need of Data Structures


As applications are getting complexed and amount of data is increasing
day by day, there may arise the following problems:

Processor speed: To handle very large amount of data, high speed


processing is required, but as the data is growing day by day to the
billions of files per entity, processor may fail to deal with that much
amount of data.

Data Search: Consider an inventory size of 106 items in a store, if our


application needs to search for a particular item, it needs to traverse 106
items every time, results in slowing down the search process.
Multiple requests: If thousands of users are searching the data
simultaneously on a web server, then there are the chances that a very
large server can be failed during that process In order to solve the above
problems, data structures are used.

Data is organized to form a data structure in such a way that all items are
not required to be searched and required data can be searched instantly.

Advantages of Data Structures


Efficiency: Efficiency of a program depends upon the choice of data
structures.

For example:

suppose, we have some data and we need to perform the search for a
particular record. In that case, if we organize our data in an array, we will
have to search sequentially element by element. hence, using array may
not be very efficient here.

There are better data structures which can make the search process
efficient like ordered array, binary search tree or hash tables.

Reusability: Data structures are reusable, i.e. once we have


implemented a particular data structure, we can use it at any other place.
Implementation of data structures can be compiled into libraries which can
be used by different clients.

Abstraction: Data structure is specified by the ADT which provides a


level of abstraction. The client program uses the data structure through
interface only, without getting into the implementation details

Data Structure Classification


1. Linear Data Structure : Data structure in which data elements are
arranged sequentially or linearly, where each element is attached to its
previous and next adjacent elements, is called a linear data structure.
Example: Array, Stack, Queue, Linked List, etc.
2. Static Data Structure: Static data structure has a fixed memory size.
It is easier to access the elements in a static data structure.
Example: array.
3. Dynamic Data Structure: In dynamic data structure, the size is not
fixed. It can be randomly updated during the runtime which may be
considered efficient concerning the memory (space) complexity of the
code.
Example: Queue, Stack, etc.
4. Non-Linear Data Structure: Data structures where data elements
are not placed sequentially or linearly are called non-linear data
structures. In a non-linear data structure, we can’t traverse all the
elements in a single runonly.
Examples: Trees and Graphs.
Figure: 1. Contiguous and Non-Contiguous data structures

Figure 2: Examples of Contiguous data structures

Figure 3: Examples of Non-Contiguous data structures


Stacks: A stack is a data structure in which elements are added to or deleted
from a single end called as Top of the stack. The elements last inserted is the
first to be removed, therefore stack is said to follow the Last In First Out
principle, LIFO. In this context, the insert operation is more commonly known as
Push and deletes operation as Pop. Other operations on a stack are: to find size
of stack, return top most element, search for an element in the stack etc.Stacks
are used in: Function calls, Recursion, Evaluation of expressions by compilers,
undo mechanism in an editor, etc
Figure 1: illustrates the operations carried out on a stack.

Figure 4. Operations on a stack


QUEUES: A queue is a linear data structure in which elements can be
inserted and deleted from two different ends. The end at which elements are
inserted into queue is referred to as Rear and the end from which elements
are deleted is known as Front. The element first inserted will be the first to
delete, therefore queue is said to follow, First In First Out, FIFO principle.
Queues are used: in processor scheduling, request processing systems, etc.
A queue can be implemented using arrays or linked representation

A queue can be implemented using arrays with different constraints on the


front and rear pointers.
Front fixed and Rear Variable: in this representation, rear pointer is
variable, whereas front pointer is fixed, which means that front always point
to the array index 0. Hence each deletion on a queue causes the elements
from index 1 to rear to move one position down, backward movement of
data.
Front and Rear Variable: in this representation, front is made variable,
and every deletion on a queue causes the front pointer to migrate or
advance to next location. At one particular point, the front may be greater
than 0, rear is at capacity, does it mean that queue is full? Whenever front is
non zero and rear reaches capacity, the queue is not full but it can
accommodate elements at starting indices of array from 0 to front-1. But to
use these locations, we need to either shift elements from front to rear to
positions starting from 0, which results in increased time complexity of
delete operation. To overcome this wastage of space and increase in time
complexity, we imagine the queue to be circular, such that two ends of the
queue meet each other.
Insert and delete operations on a queue when Front (Head) is
variable.
Linked Lists:
A linked list is a collection of nodes which contain data elements as
well as the information about where the next element in the list is
stored. Each element is stored using a node format, which contains
two fields: data and link. Data field contains the information and Link
filed contains a pointer to the address of next element in the list.

Figure: Linked List Node Structure


Operations on Linked Lists:
Insert: Insert at first position, insert at last
position, insert into ordered list Delete:
Delete an element from first, last or any
intermediate position Traverse List: print the
list
Copy the linked List, Reverse the linked list, search for an element in
the list, etc
Types of Linked Lists:
Singly Linked List:

 It is a basic type of linked list.


 Each node contains data and pointer to next node and last
node’s pointer is NULL.
 Limitation of SLL is that we can traverse the list in only one
direction, forward direction.

Figure : Single Linked List


Circular Linked List:
 CLL is a SLL where last node points to first node in the list
 It does not contain null pointers like SLL
 We can traverse the list in only one direction

 Its advantage is that when we want to go from last node


to first node, it directly points to first node

Figure: CLL

Doubly Linked List:


 Each node of doubly linked list contains data and two
pointer fields, pointer to previous and next node.

 Advantage of DLL is that we can traverse the list any direction,


forward or reverse.
 Other advantages of DLL are that we can delete a node
with little trouble, since we have pointers to the previous
and next nodes. A node on a SLL cannot be removed
unless we have pointer to its predecessor.

1
Inserting into a SLL:

Deleting from a SLL:

Trees: A tree is a structure in which each node can have multiple


successors (unlike the linear structures that we have been studying so far,
in which each node always had at most one successor). The first node in a
tree s called a root, it is often called the top level node (YES, in computer
science root of a tree is at the top of a tree). In a tree, there is always a
unique path from the root of a tree to every other node in a tree – this has
an important consequence: there are no cycles in a tree (think of a cycle
as a closed path that allows us to go in a cycle infinitely many times).

An example of a Tree with 15 nodes

Binary Search Tree: A binary search tree is a binary tree


which may be empty. If not empty, it satisfies the following
2
properties:
1. Every element has a key and no two elements have the same key .
2. The keys (if any) in the left subtree are smaller than the key in the
root
3. The keys (if any) in the right subtree are greater than the key in
the root
4. The left and right subtrees are binary search trees.

Figure 13: Binary Search Tree on Numbers Figure 14: Binary Search Tree on Strings

Graphs:
Let V be a finite set, and denote by E(V) = {{u, v} | u, v ∈ V, u ≠v}

DEFINITION. A pair G = (V, E) with E ⊆ E(V) is called a


graph (on V). The elements of V are the vertices of G,
and those of E the edges of G. The vertex set of a graph
G

A graph G can be represented as a plane figure by drawing a


line (or a curve) between the points u and v (representing
vertices) if e = uv is an edge of G. The figure on the right is a
geometric representation of the graph G with VG = {v1, v2,
v3, v4, v5, v6} and EG = {v1v2, v1v3, v2v3,

3
v2v4, v5v6}.

Definition of Algorithm
The word Algorithm means” A set of finite rules or
instructions to be followed in calculations or other
problem-solving operations”

Or

” A procedure for solving a mathematical problem in a


finite number of steps that frequently involves recursive
operations”.

Therefore, Algorithm refers to a sequence of finite steps to


solve a particular problem.

What are the Characteristics of an Algorithm?

4
How to Design an Algorithm?
To write an algorithm, the following things are needed as a pre-
requisite:
1. The problem that is to be solved by this algorithm i.e. clear
problem definition.
2. The constraints of the problem must be considered while
solving the problem.
3. The input to be taken to solve the problem.
4. The output is to be expected when the problem is solved.
5. The solution to this problem is within the given
constraints.

23CS1412- PRINCIPLES OF DATA STRUCTURES LABORATORY


5
LTPC
0042
COURSE OBJECTIVE:
● Knowledge of basic Data Structures and their implementations.
● Skills to apply appropriate Data Structures in problem solving.
● Strength and weakness of different Data Structures.
● Importance of Data Structures in context of writing efficient programs.
LIST OF EXPERIMENTS
1. Write a program to implement the Stack operations.
2. Write a program to implement the Queue operations.
3. Write a program to implement the operations on Singly Linked List.
4. Write a program to implement the operations on Doubly Linked List.
5. Write a program to implement the operations on Circular Linked List.
6. Write a Program to perform the given operations on Trees.
a) Insertion
b) Deletion
c) Searching
7. Write a Program to implement the following Tree Traversals Methods
a) Pre-order
b) In-order
c) Post-order
8. Write a program to implement the following Graph Traversal Methods
a) Breadth First Search
b) Depth First Search
9. Write a program to implement Minimum Spanning Tree using the
following
algorithms
a) Prim’s Algorithm
b) Kruskal’s Algorithm
10. Write a Program to implement Single Source Shortest Path algorithm
using
Dijkstra’s algorithm.
11. Write a program to sort the given list of elements using Quick Sort and
Merge Sort.
12. Write a program to search an element in the given list of elements
using Linear
Search and Binary Search.

TOTAL: 60 PERIODS

COURSE OUTCOMES:
6
Upon successful completion of the course, student will be able to;
CO1 Understand the concept of Stacks and Queues and its application
CO2 Explain the concept of Queues and its application.
CO3 Study about different types of Tree along with their operations and
applications.
CO4 Solve problem involving Graphs and its applicability.
CO5 Design efficient algorithms for Sorting.
CO6 Implement efficient algorithms for Searching

23CS1412- PRINCIPLES OF DATA STRUCTURES LABORATORY


7
INDEX

S.no Program. Name Page.no

1 Program to implement the Stack operations


2 Program to implement the Queue operations
program to implement the operations on Singly
3
Linked List
program to implement the operations on Doubly
4
Linked List
program to implement the operations on Circular
5 Linked List.

Program to perform the given operations on Trees


6 a) Insertion
b) Deletion
c) Searching
Program to implement the following Tree Traversals Methods

7 a) Pre-order
b) In-order
c) Post-order
Program to implement the following Graph Traversal Methods
8 a)Breadth First Search
b) Depth First Search
Program to implement Minimum Spanning Tree
using the following
9 algorithms
a) Prim’s Algorithm
b) Kruskal’s Algorithm
Program to implement Single Source Shortest Path
10
algorithm using Dijkstra’s algorithm.
Program to search an element in the given list of elements using
searching algorithm
11 a Linear Search

b Binary Search

Program to sort the given list of elements using sorting algorithm


12 c Quick Sort
d Merge Sort

8
Ex. no.: 1 STACK OPERATION

AIM:
To Write a C program to implement the Stack operations

ALGORITHM:
1.Start
2. Define a array stack of size max = 4
3. Initialize top = -1
4. Display a menu listing stack operations
5. Accept choice
6. If choice = 1 then
7. If top < SIZE -1
8. Increment top
9. Store element at current position of top
10. Else
11. Print Stack overflow
12. If choice = 2 then
13. If top < 0 then
14. Print Stack underflow
15. Else
16. Display current top element
17. Decrement top
18. If choice = 3 then
19. Display stack elements starting from top
20. Stop

PROGRAM:
#include <stdio.h>
#include <stdlib.h>
#define SIZE 4
int top = -1, inp_array[SIZE];
void push();
void pop();
void show();

int main()
{
int choice;

while (1)
{
printf("\nPerform operations on the stack:");
printf("\n1.Push the element\n2.Pop the element\n3.Show\n4.End");
printf("\n\nEnter the choice: ");
scanf("%d", &choice);

switch (choice)
{
case 1:
9
push();
break;
case 2:
pop();
break;
case 3:
show();
break;
case 4:
exit(0);

default:
printf("\nInvalid choice!!");
}
}
}

void push()
{
int x;

if (top == SIZE - 1)
{
printf("\nOverflow!!");
}
else
{
printf("\nEnter the element to be added onto the stack: ");
scanf("%d", &x);
top = top + 1;
inp_array[top] = x;
}
}

void pop()
{
if (top == -1)
{
printf("\nUnderflow!!");
}
else
{
printf("\nPopped element: %d", inp_array[top]);
top = top - 1;
}
}

void show()
{
if (top == -1)
10
{
printf("\nUnderflow!!");
}
else
{
printf("\nElements present in the stack: \n");
for (int i = top; i >= 0; --i)
printf("%d\n", inp_array[i]);
}
}
Output:
Perform operations on the stack:
1.Push the element
2.Pop the element
3.Show
4.End

Enter the choice: 1

Enter the element to be added onto the stack: 1

Perform operations on the stack:


1.Push the element
2.Pop the element
3.Show
4.End

Enter the choice: 1

Enter the element to be added onto the stack: 2

Perform operations on the stack:


1.Push the element
2.Pop the element
3.Show
4.End

Enter the choice: 3

Elements present in the stack:


2
1

Perform operations on the stack:


1.Push the element
2.Pop the element
3.Show
4.End

Enter the choice: 2


11
Popped element: 2
Perform operations on the stack:
1.Push the element
2.Pop the element
3.Show
4.End

Enter the choice: 3

Elements present in the stack:


1

Perform operations on the stack:


1.Push the element
2.Pop the element
3.Show
4.End

Enter the choice:

RESULT :-
Thus the program has been successfully executed and
verified .

12
Ex. no.: 2 QUEUE OPERATION

AIM:
To Write a C program to implement the Queue operations.

ALGORITHM:
1. Start
2. Define a array queue of size max = 5
3. Initialize front = rear = –1
4. Display a menu listing queue operations
5. Accept choice
6. If choice = 1 then
7. If rear < size -1
8. Increment rear
9. Store element at current position of rear
10. Else
11. Print Queue Full
12. If choice = 2 then
13. If front = –1 then
14. Print Queue empty
15. Else
16. Display current front element
17. Increment front
18. If choice = 3 then
19. Display queue elements
PROGRAM :
#include <stdio.h>
# define SIZE 100
void enqueue();
void dequeue();
void show();
int inp_arr[SIZE];
int Rear = - 1;
int Front = - 1;
main()
{
int ch;
while (1)
{
printf("1.Enqueue Operation\n");
printf("2.Dequeue Operation\n");
printf("3.Display the Queue\n");
printf("4.Exit\n");
printf("Enter your choice of operations : ");
scanf("%d", &ch);
switch (ch)
{
case 1:
enqueue();
13
break;
case 2:
dequeue();
break;
case 3:
show();
break;
case 4:
exit(0);
default:
printf("Incorrect choice \n");
}
}
}

void enqueue()
{
int insert_item;
if (Rear == SIZE - 1)
printf("Overflow \n");
else
{
if (Front == - 1)

Front = 0;
printf("Element to be inserted in the Queue\n : ");
scanf("%d", &insert_item);
Rear = Rear + 1;
inp_arr[Rear] = insert_item;
}
}

void dequeue()
{
if (Front == - 1 || Front > Rear)
{
printf("Underflow \n");
return ;
}
else
{
printf("Element deleted from the Queue: %d\n", inp_arr[Front]);
Front = Front + 1;
}
}

void show()
{

if (Front == - 1)
14
printf("Empty Queue \n");
else
{
printf("Queue: \n");
for (int i = Front; i <= Rear; i++)
printf("%d ", inp_arr[i]);
printf("\n");
}
}
Output:
1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 1
Element to be inserted in the Queue: 10

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 1
Element to be inserted in the Queue: 20

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 3
Queue:
10 20

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations : 2
Element deleted from the Queue: 10

1.Enqueue Operation
2.Dequeue Operation
3.Display the Queue
4.Exit
Enter your choice of operations: 3
Queue:
20

RESULT : -

15
Thus the program has been successfully executed and
verified.

16
Ex. no.: 3 SINGLY LINKED LIST

AIM:
To Write a C program to Perform operations on Singly Linked
List

ALGORITHM:
1. Start
2. Define single linked list node as self referential structure
3. Display menu on list operation
5. Accept user choice
6. If choice = 1 then
7. Locate node after which insertion is to be done
8. Create a new node and get data part
9. Insert the new node at appropriate position by manipulating address
10. Else if choice = 3
11. Get node's data to be insert in last position.
12. Locate the node and delink the node
13. Rearrange the links
14. Else
15.Traverse the list from Head node to node which points to null
16. Stop
PROGRAM:
Singly linked lsit
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int count=0;
struct node
{
int data;
struct node *next;
}*head,*newn,*trav;
//----------------------------------------------------------
void create_list()
{
int value;
struct node *temp;
temp=head;
newn=(struct node *)malloc(sizeof (struct node));
printf("\nenter the value to be inserted");
scanf("%d",&value);
newn->data=value;
if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
}
else
17
{
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newn;
newn->next=NULL;
count++;
}
}
//----------------------------------------------------
void insert_at_begning(int value)
{
newn=(struct node *)malloc(sizeof (struct node));
newn->data=value;
if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
}
else
{
newn->next=head;
head=newn;
count++;
}
}
//----------------------------------------------------------
void insert_at_end(int value)
{
struct node *temp;
temp=head;
newn=(struct node *)malloc(sizeof (struct node));
newn->data=value;
if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
}
else
{
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newn;
newn->next=NULL;
count++;
18
}
}
//------------------------------------------------------
int insert_at_middle()
{
if(count>=2)
{
struct node *var1,*temp;
int loc,value;
printf("\n after which value you want to insert : ");
scanf("%d",&loc);
printf("\nenter the value to be inserted");
scanf("%d",&value);
newn=(struct node *)malloc(sizeof (struct node));
newn->data=value;
temp=head;
/* if(head==NULL)
{
head=newn;
head->next=NULL;
count++;
return 0;
}
else
{*/
while(temp->data!=loc)
{
temp=temp->next;
if(temp==NULL)
{
printf("\nSORRY...there is no %d element",loc);
return 0;
}
}
//var1=temp->next;
newn->next=temp->next;//var1;
temp->next=newn;
count++;
//}
}
else
{
printf("\nthe no of nodes must be >=2");
}
}
//----------------------------------------------------------------
int delete_from_middle()
{
if(count==0)
printf("\n List is Empty!!!! you can't delete elements\n");
19
else if(count>2)
{
struct node *temp,*var;
int value;
temp=head;
printf("\nenter the data that you want to delete from the list shown
above");
scanf("%d",&value);
while(temp->data!=value)
{
var=temp;
temp=temp->next;
if(temp==NULL)
{
printf("\nSORRY...there is no %d element",value);
return 0;
}
}
if(temp==head)
{
head=temp->next;
}
else{
var->next=temp->next;
temp->next=NULL;
}
count--;
if(temp==NULL)
printf("Element is not avilable in the list \n**enter only middle
elements..**");
else
printf("\ndata deleted from list is %d",value);
free(temp);
}
else
{
printf("\nthere no middle elemts..only %d elemts is avilable\n",count);
}
}
//------------------------------------------------------------------
int delete_from_front()
{
struct node *temp;
temp=head;
if(head==NULL)
{
printf("\nno elements for deletion in the list\n");
return 0;
}
else
20
{
printf("\ndeleted element is :%d",head->data);
if(temp->next==NULL)
{
head=NULL;
}
else{
head=temp->next;
temp->next=NULL;
}
count--;
free(temp);
}
}
//--------------------------------------------------------
int delete_from_end()
{
struct node *temp,*var;
temp=head;
if(head==NULL)
{
printf("\nno elemts in the list");
return 0;
}
else{
if(temp->next==NULL )
{
head=NULL;//temp->next;
}
else{
while(temp->next != NULL)
{
var=temp;
temp=temp->next;
}
var->next=NULL;
}
printf("\ndata deleted from list is %d",temp->data);
free(temp);
count--;
}
return 0;
}
//------------------------------------------------------
int display()
{
trav=head;
if(trav==NULL)
{
printf("\nList is Empty\n");
21
return 0;
}
else
{
printf("\n\nElements in the Single Linked List is %d:\n",count);
while(trav!=NULL)
{
printf(" -> %d ",trav->data);
trav=trav->next;
}
printf("\n");
}
}
//---------------------------------------------------------------
int main()
{
int ch=0;
char ch1;
head=NULL;
while(1)
{
printf("\n1.create linked list");
printf("\n2.insertion at begning of linked list");
printf("\n3.insertion at the end of linked list");
printf("\n4.insertion at the middle where you want");
printf("\n5.deletion from the front of linked list");
printf("\n6.deletion from the end of linked list ");
printf("\n7.deletion of the middle data that you want");
printf("\n8.display the linked list");
printf("\n9.exit\n");
printf("\nenter the choice of operation to perform on linked list");
scanf("%d",&ch);
switch(ch)
{
case 1:
{
do{
create_list();
display();
printf("do you want to create list ,y / n");
getchar();
scanf("%c",&ch1);
}while(ch1=='y');
break;
}
case 2:
{
int value;
printf("\nenter the value to be inserted");
scanf("%d",&value);
22
insert_at_begning(value);
display();
break;
}
case 3:
{
int value;
printf("\nenter value to be inserted");
scanf("%d",&value);
insert_at_end(value);
display();
break;
}
case 4:
{
insert_at_middle();
display();
break;
}
case 5:
{
delete_from_front();
display();
}break;
case 6:
{
delete_from_end();
display();
break;
}
case 7:
{
display();
delete_from_middle();
display();
break;
}
case 8:
{
display();
break;
}
case 9:
{
exit(1);
}
default:printf("\n****Please enter correct choice****\n");
}
}
getch();
23
}
Output:
1.create linked list
2.insertion at beginning of linked list
3.insertion at the end of linked list
4.insertion at the middle where you want
5.deletion from the front of linked list
6.deletion from the end of linked list
7.deletion of the middle data that you want
8.display the linked list
9.exit

enter the choice of operation to perform on linked list1

enter the value to be inserted12

Elements in the Single Linked List is 1:


-> 12
do you want to create list ,y / ny

enter the value to be inserted1

Elements in the Single Linked List is 2:


-> 12 -> 1
do you want to create list ,y / nn

1.create linked list


2.insertion at begning of linked list
3.insertion at the end of linked list
4.insertion at the middle where you want
5.deletion from the front of linked list
6.deletion from the end of linked list
7.deletion of the middle data that you want
8.display the linked list
9.exit

enter the choice of operation to perform on linked list2

enter the value to be inserted20

Elements in the Single Linked List is 3:


-> 20 -> 12 -> 1

1.create linked list


2.insertion at begning of linked list
3.insertion at the end of linked list
4.insertion at the middle where you want
24
5.deletion from the front of linked list
6.deletion from the end of linked list
7.deletion of the middle data that you want
8.display the linked list
9.exit

enter the choice of operation to perform on linked list3

enter value to be inserted60

Elements in the Single Linked List is 4:


-> 20 -> 12 -> 1 -> 60

1.create linked list


2.insertion at begning of linked list
3.insertion at the end of linked list
4.insertion at the middle where you want
5.deletion from the front of linked list
6.deletion from the end of linked list
7.deletion of the middle data that you want
8.display the linked list
9.exit

enter the choice of operation to perform on linked list4

after which value you want to insert : 89

enter the value to be inserted90

SORRY...there is no 89 element

Elements in the Single Linked List is 4:


-> 20 -> 12 -> 1 -> 60

1.create linked list


2.insertion at begning of linked list
3.insertion at the end of linked list
4.insertion at the middle where you want
5.deletion from the front of linked list
6.deletion from the end of linked list
7.deletion of the middle data that you want
8.display the linked list
9.exit

enter the choice of operation to perform on linked list4

after which value you want to insert : 12

enter the value to be inserted90


25
Elements in the Single Linked List is 5:
-> 20 -> 12 -> 90 -> 1 -> 60

1.create linked list


2.insertion at begning of linked list
3.insertion at the end of linked list
4.insertion at the middle where you want
5.deletion from the front of linked list
6.deletion from the end of linked list
7.deletion of the middle data that you want
8.display the linked list
9.exit

enter the choice of operation to perform on linked list5

deleted element is :20

Elements in the Single Linked List is 4:


-> 12 -> 90 -> 1 -> 60

1.create linked list


2.insertion at begning of linked list
3.insertion at the end of linked list
4.insertion at the middle where you want
5.deletion from the front of linked list
6.deletion from the end of linked list
7.deletion of the middle data that you want
8.display the linked list
9.exit

enter the choice of operation to perform on linked list6

data deleted from list is 60

Elements in the Single Linked List is 3:


-> 12 -> 90 -> 1

1.create linked list


2.insertion at begning of linked list
3.insertion at the end of linked list
4.insertion at the middle where you want
5.deletion from the front of linked list
6.deletion from the end of linked list
7.deletion of the middle data that you want
8.display the linked list
9.exit

enter the choice of operation to perform on linked list7


26
Elements in the Single Linked List is 3:
-> 12 -> 90 -> 1

enter the data that you want to delete from the list shown above90

data deleted from list is 90

Elements in the Single Linked List is 2:


-> 12 -> 1

1.create linked list


2.insertion at begning of linked list
3.insertion at the end of linked list
4.insertion at the middle where you want
5.deletion from the front of linked list
6.deletion from the end of linked list
7.deletion of the middle data that you want
8.display the linked list
9.exit

enter the choice of operation to perform on linked list8

Elements in the Single Linked List is 2:


-> 12 -> 1

1.create linked list


2.insertion at begning of linked list
3.insertion at the end of linked list
4.insertion at the middle where you want
5.deletion from the front of linked list
6.deletion from the end of linked list
7.deletion of the middle data that you want
8.display the linked list
9.exit

enter the choice of operation to perform on linked list


=== Session Ended. Please Run the code again ===
RESULT :-

Thus the program has been successfully executed and


verified .

27
Ex. no.: 4 DOUBLY LINKED LIST

AIM:
To Write a C program to perform the operations on Doubly Linked
List
ALGORITHM:
1. Creation: Start with an empty doubly linked list. Allocate memory for
the head node. Set the prev and next pointers of the head node to
NULL. Optionally, assign initial data to the head node.
2. Insertion at the beginning: Create a new node with the given data.
If the list is empty, set the head pointer to the new node. Otherwise,
set the next pointer of the new node to the current head. Set the prev
pointer of the current head to the new node. Update the head pointer
to point to the new node.
3. Insertion at the end: Create a new node with the given data. If the
list is empty, set the head pointer to the new node. Otherwise, traverse
the list to find the last node. Set the next pointer of the last node to the
new node. Set the prev pointer of the new node to point to the last
node.
4. Deletion: Search for the node to be deleted by traversing the list. If
the node is found, update the next pointer of the previous node to skip
the node to be deleted. If the node to be deleted is the head node,
update the head pointer. Free the memory allocated for the node to be
deleted.
PROGRAM:

#include<stdio.h>
#include<stdlib.h>
struct node
{
struct node *prev;
struct node *next;
int data;
};
struct node *head;
void insertion_beginning();
void insertion_last();
void insertion_specified();
void deletion_beginning();
void deletion_last();
void deletion_specified();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 9)
{
printf("\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
28
printf("\
n============================================
===\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Insert at any random
location\n4.Delete from Beginning\n
5.Delete from last\n6.Delete the node after the given data\n7.Search\
n8.Show\n9.Exit\n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
insertion_beginning();
break;
case 2:
insertion_last();
break;
case 3:
insertion_specified();
break;
case 4:
deletion_beginning();
break;
case 5:
deletion_last();
break;
case 6:
deletion_specified();
break;
case 7:
search();
break;
case 8:
display();
break;
case 9:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void insertion_beginning()
{
struct node *ptr;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
29
printf("\nOVERFLOW");
}
else
{
printf("\nEnter Item value");
scanf("%d",&item);

if(head==NULL)
{
ptr->next = NULL;
ptr->prev=NULL;
ptr->data=item;
head=ptr;
}
else
{
ptr->data=item;
ptr->prev=NULL;
ptr->next = head;
head->prev=ptr;
head=ptr;
}
printf("\nNode inserted\n");
}

}
void insertion_last()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *) malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter value");
scanf("%d",&item);
ptr->data=item;
if(head == NULL)
{
ptr->next = NULL;
ptr->prev = NULL;
head = ptr;
}
else
{
temp = head;
while(temp->next!=NULL)
30
{
temp = temp->next;
}
temp->next = ptr;
ptr ->prev=temp;
ptr->next = NULL;
}

}
printf("\nnode inserted\n");
}
void insertion_specified()
{
struct node *ptr,*temp;
int item,loc,i;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\n OVERFLOW");
}
else
{
temp=head;
printf("Enter the location");
scanf("%d",&loc);
for(i=0;i<loc;i++)
{
temp = temp->next;
if(temp == NULL)
{
printf("\n There are less than %d elements", loc);
return;
}
}
printf("Enter value");
scanf("%d",&item);
ptr->data = item;
ptr->next = temp->next;
ptr -> prev = temp;
temp->next = ptr;
temp->next->prev=ptr;
printf("\nnode inserted\n");
}
}
void deletion_beginning()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
31
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
head = head -> next;
head -> prev = NULL;
free(ptr);
printf("\nnode deleted\n");
}

}
void deletion_last()
{
struct node *ptr;
if(head == NULL)
{
printf("\n UNDERFLOW");
}
else if(head->next == NULL)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}
else
{
ptr = head;
if(ptr->next != NULL)
{
ptr = ptr -> next;
}
ptr -> prev -> next = NULL;
free(ptr);
printf("\nnode deleted\n");
}
}
void deletion_specified()
{
struct node *ptr, *temp;
int val;
printf("\n Enter the data after which the node is to be deleted : ");
scanf("%d", &val);
ptr = head;
while(ptr -> data != val)
32
ptr = ptr -> next;
if(ptr -> next == NULL)
{
printf("\nCan't delete\n");
}
else if(ptr -> next -> next == NULL)
{
ptr ->next = NULL;
}
else
{
temp = ptr -> next;
ptr -> next = temp -> next;
temp -> next -> prev = ptr;
free(temp);
printf("\nnode deleted\n");
}
}
void display()
{
struct node *ptr;
printf("\n printing values...\n");
ptr = head;
while(ptr != NULL)
{
printf("%d\n",ptr->data);
ptr=ptr->next;
}
}
void search()
{
struct node *ptr;
int item,i=0,flag;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
while (ptr!=NULL)
{
if(ptr->data == item)
{
printf("\nitem found at location %d ",i+1);
flag=0;
break;
}
33
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
if(flag==1)
{
printf("\nItem not found\n");
}
}

}
Output:

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


8

printing values...

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
34
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


1

Enter Item value12

Node inserted

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


1

Enter Item value123

Node inserted

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
35
8.Show
9.Exit

Enter your choice?


1

Enter Item value1234

Node inserted

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


8

printing values...
1234
123
12

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
36
9.Exit

Enter your choice?


2

Enter value89

node inserted

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


3
Enter the location1
Enter value12345

node inserted

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

37
Enter your choice?
8

printing values...
1234
123
12345
12
89

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


4

node deleted

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


38
5

node deleted

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


8

printing values...
123
12345

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


6

Enter the data after which the node is to be deleted : 123

39
*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


8

printing values...
123

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


7

Enter item which you want to search?


123

item found at location 1


*********Main Menu*********

Choose one option from the following list ...


40
============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


6

Enter the data after which the node is to be deleted : 123

Can't delete

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Insert at any random location
4.Delete from Beginning
5.Delete from last
6.Delete the node after the given data
7.Search
8.Show
9.Exit

Enter your choice?


9

Exited..
RESULT : -

Thus the program has been successfully executed and


verified .

41
Ex. no.: 5 CIRCULAR LINKED LIST

AIM:
To Write a C program to perform the operations on Circular Linked
List.

ALGORITHM:

1. Creation: Allocate memory for the head node and assign it the given
data. Set the next pointer of the head node to point to itself.
2. Insertion at the beginning: Create a new node with the given data.
If the list is empty, set the head pointer to the new node and make it
circular. Otherwise, traverse the list to find the last node. Set the next
pointer of the last node to the new node. Set the next pointer of the
new node to point to the head node. Update the head pointer to point
to the new node.
3. Deletion: If the list is empty, print a message indicating that there's
nothing to delete. Traverse the list to find the node with the given data
or until we reach the end of the list. If the node is not found, print a
message indicating that the element is not found in the list. If the node
to be deleted is the head node and the list contains only one node, set
the head pointer to NULL. If the node to be deleted is the head node,
traverse the list to find the last node and update its next pointer. If the
node to be deleted is not the head node and not the last node, update
the next pointer of the previous node to skip the node to be deleted.
Free the memory allocated for the node to be deleted.
PROGRAM:
#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *head;

void beginsert ();


void lastinsert ();
void randominsert();
void begin_delete();
void last_delete();
void random_delete();
void display();
void search();
void main ()
{
int choice =0;
while(choice != 7)
{
42
printf("\n*********Main Menu*********\n");
printf("\nChoose one option from the following list ...\n");
printf("\
n============================================
===\n");
printf("\n1.Insert in begining\n2.Insert at last\n3.Delete from
Beginning\n4.Delete from last\n5.Search for an element\n6.Show\n7.Exit\
n");
printf("\nEnter your choice?\n");
scanf("\n%d",&choice);
switch(choice)
{
case 1:
beginsert();
break;
case 2:
lastinsert();
break;
case 3:
begin_delete();
break;
case 4:
last_delete();
break;
case 5:
search();
break;
case 6:
display();
break;
case 7:
exit(0);
break;
default:
printf("Please enter valid choice..");
}
}
}
void beginsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW");
}
else
{
printf("\nEnter the node data?");
43
scanf("%d",&item);
ptr -> data = item;
if(head == NULL)
{
head = ptr;
ptr -> next = head;
}
else
{
temp = head;
while(temp->next != head)
temp = temp->next;
ptr->next = head;
temp -> next = ptr;
head = ptr;
}
printf("\nnode inserted\n");
}

}
void lastinsert()
{
struct node *ptr,*temp;
int item;
ptr = (struct node *)malloc(sizeof(struct node));
if(ptr == NULL)
{
printf("\nOVERFLOW\n");
}
else
{
printf("\nEnter Data?");
scanf("%d",&item);
ptr->data = item;
if(head == NULL)
{
head = ptr;
ptr -> next = head;
}
else
{
temp = head;
while(temp -> next != head)
{
temp = temp -> next;
}
temp -> next = ptr;
ptr -> next = head;
}

44
printf("\nnode inserted\n");
}

void begin_delete()
{
struct node *ptr;
if(head == NULL)
{
printf("\nUNDERFLOW");
}
else if(head->next == head)
{
head = NULL;
free(head);
printf("\nnode deleted\n");
}

else
{ ptr = head;
while(ptr -> next != head)
ptr = ptr -> next;
ptr->next = head->next;
free(head);
head = ptr->next;
printf("\nnode deleted\n");

}
}
void last_delete()
{
struct node *ptr, *preptr;
if(head==NULL)
{
printf("\nUNDERFLOW");
}
else if (head ->next == head)
{
head = NULL;
free(head);
printf("\nnode deleted\n");

}
else
{
ptr = head;
while(ptr ->next != head)
{
preptr=ptr;
45
ptr = ptr->next;
}
preptr->next = ptr -> next;
free(ptr);
printf("\nnode deleted\n");

}
}

void search()
{
struct node *ptr;
int item,i=0,flag=1;
ptr = head;
if(ptr == NULL)
{
printf("\nEmpty List\n");
}
else
{
printf("\nEnter item which you want to search?\n");
scanf("%d",&item);
if(head ->data == item)
{
printf("item found at location %d",i+1);
flag=0;
}
else
{
while (ptr->next != head)
{
if(ptr->data == item)
{
printf("item found at location %d ",i+1);
flag=0;
break;
}
else
{
flag=1;
}
i++;
ptr = ptr -> next;
}
}
if(flag != 0)
{
printf("Item not found\n");
}
}
46
}

void display()
{
struct node *ptr;
ptr=head;
if(head == NULL)
{
printf("\nnothing to print");
}
else
{
printf("\n printing values ... \n");

while(ptr -> next != head)


{

printf("%d\n", ptr -> data);


ptr = ptr -> next;
}
printf("%d\n", ptr -> data);
}

}
Output:

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit

Enter your choice?


1

Enter the node data?10

node inserted

*********Main Menu*********
47
Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit

Enter your choice?


2

Enter Data?20

node inserted

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit

Enter your choice?


2

Enter Data?30

node inserted

*********Main Menu*********

Choose one option from the following list ...

============================================
===

48
1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit

Enter your choice?


3

node deleted

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit

Enter your choice?


4

node deleted

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit

Enter your choice?


5
49
Enter item which you want to search?
20
item found at location 1
*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit

Enter your choice?


6

printing values ...


20

*********Main Menu*********

Choose one option from the following list ...

============================================
===

1.Insert in begining
2.Insert at last
3.Delete from Beginning
4.Delete from last
5.Search for an element
6.Show
7.Exit

Enter your choice?


7

RESULT :-

Thus the program has been successfully executed and


verified .

50
51
Ex. no.: 6 BINARY TREE

AIM:
To Write a C program to perform the operations on binary tree.

ALGORITHM:

a. Creation
1. Read data and store in a variable called as key
2. Allocate memory for a new node using malloc, specifying the size
for a single struct Node.
3. Assign the input to the data variable of the new node.
4. Set the ltree and rtree pointers to NULL, indicating this is a leaf node
or a new node with no children.
b. Insert an element in the Binary Search Tree
1. If the value of the new node is less than the root node then, it will be
inserted to the left subtree.
2. If the value of the new node is greater than root node then, it will be
inserted to the right subtree.

c. Delete an element in the BST


Deletion in a binary search tree can be divided into three cases:
a. If the node to be deleted is a leaf node then, parent of that node will
point to null.
b. If the node to be deleted has one child node, then child node will
become a child node of the parent node
c. If the node to be deleted has two children then, find the node with
minimum value from the right subtree of that current node(i.e. node
to be deleted). The current node will be replaced by this minimum
value.

d. Traverse the Binary Search Tree in Inorder, Preorder and


Post Order
i) Inorder
 Traverse the left subtree
 Visit the root.
 Traverse the right subtree
ii) Preorder
52
 Visit the root
 Traverse the left subtree
 Traverse the right subtree
iii) Postorder
 Traverse the left subtree
 Traverse the right subtree
 Visit the root

e. Search the Binary Search Tree for a given element (KEY).


1. Compare the searchable element(KEY) to the tree's root node.
2. Return the root node if the value of the element being searched
matches the value of the root node.
3. If the value is not the same, see if it is smaller than the root element,
and if so, navigate to the left subtree.
4. Explore the appropriate subtree if it is greater than the root element.
5. Return NULL if the element isn't present throughout the entire tree.

PROGRAM:

#include<stdio.h>
#include<stdlib.h>
Include<conio.h>
#define MAX_SIZE 25
#define max(a, b) a>b ? a : b

struct TreeNode
{
int val;
struct TreeNode* left;
struct TreeNode* right;
};

// global root declaration


struct TreeNode* root = NULL;

// function prototyping
void insert(int);
void delete(int);
int search(int);
int height(struct TreeNode*);
void inorder(struct TreeNode*);
void preorder(struct TreeNode*);
void postorder(struct TreeNode*);
void levelorder();

53
int main()
{
int user_choice, node_data;
char g='Y';

do
{
printf("\n\n--- Binary Tree --\n\n");
printf("\n1. Insert ");
printf("\n2. Delete");
printf("\n3. Search");
printf("\n4. Height");
printf("\n5. Inorder Traversal");
printf("\n6. Preorder Traversal");
printf("\n7. Postorder Traversal");
printf("\n8. Level order Traversal");
printf("\n9. Exit");
printf("\n\nEnter Your Choice: ");
scanf("%d", &user_choice);

printf("\n");
switch(user_choice)
{
case 1:
printf("Enter data for new node: ");
scanf("%d", &node_data);
insert(node_data);
break;

case 2:
printf("Enter node data: ");
scanf("%d", &node_data);
delete(node_data);
break;

case 3:
printf("Enter node data: ");
scanf("%d", &node_data);
int has_found = search(node_data);

if(has_found == -1) {
printf("\nNode was not found!");
} else {
printf("\nNode was found");
}
break;

case 4:
printf("height of the tree is: %d", height(root));
break;
54
case 5:
printf("Inorder Traversal\n\n");
inorder(root);
break;

case 6:
printf("Preorder Traversal\n\n");
preorder(root);
break;

case 7:
printf("Postorder Traversal\n\n");
postorder(root);
break;

case 8:
printf("Level order Traversal\n\n");
levelorder();
break;

case 9:
printf("Program is terminating...\n\n");
exit(0);

default:
printf("Invalid choice");
}

printf("\n Do u want to continue:::");


scanf("\n%c", &g);
}
while(g=='y'||g=='Y');
getch();
}

struct TreeNode* create(int data)


{
struct TreeNode* new_node = (struct TreeNode*) malloc
(sizeof(struct TreeNode));
if(new_node == NULL)
{
printf("\nMemory can't be allocated for new node\n");
return NULL;
}

new_node->left = NULL;
new_node->right = NULL;
new_node->val = data;

55
return new_node;
}

// inserts a new node in the tree


void insert(int data)
{
if(root == NULL)
{
struct TreeNode* new_node = create(data);
if(new_node)
{
root = new_node;
printf("\n * Node with data %d was inserted", data);
}
return;
}

struct TreeNode* queue[MAX_SIZE];


struct TreeNode* new_node = NULL;
int front = -1;
int rear = -1;
queue[front+1] = root;
front = rear = 0;

while(front <= rear)


{
struct TreeNode* temp = queue[front];
front++;

if(temp->left != NULL)
{
queue[++rear] = temp->left;
}
else
{
new_node = create(data);
if(new_node)
{
temp->left = new_node;
printf("\n* Node with data %d was inserted", data);
}
return;
}

if(temp->right != NULL)
{
queue[++rear] = temp->right;
}
else
{
56
new_node = create(data);
if(new_node)
{
temp->right = new_node;
printf("\n* Node with data %d was inserted", data);
}
return;
}
}
}

void delete(int key)


{
if(root == NULL)
{
return;
}

if(root->left == NULL && root->right == NULL)


{
if(root->val == key)
{
root = NULL;
printf("\n* Node with data %d was deleted", key);
return;
}
else
{
return;
}
}

struct TreeNode* temp = NULL, *last_node = NULL, *key_node =


NULL;

struct TreeNode* queue[MAX_SIZE];


int front = -1;
int rear = -1;

queue[front + 1] = root;
front = rear = 0;

while (front <= rear)


{
temp = queue[front];
front++;

57
if (temp->val == key)
{
key_node = temp;
}

if (temp->left != NULL)
{
last_node = temp;
queue[++rear] = temp->left;
}

if (temp->right != NULL)
{
last_node = temp;
queue[++rear] = temp->right;
}
}

if (key_node != NULL)
{
key_node->val = temp->val;

if (last_node->right == temp)
{
last_node->right = NULL;
}
else
{
last_node->left = NULL;
}
printf("\n* Node with data %d was deleted", key);
free(temp);
return;
}
printf("\n* Node with data %d was not found", key);
}

int search(int key)


{
if (root == NULL)
{
return -1;
}
struct TreeNode* queue[MAX_SIZE];
int front = -1;
int rear = -1;

queue[front + 1] = root;
front = rear = 0;
58
while (front <= rear)
{
struct TreeNode* temp = queue[front];
front++;

if (temp->val == key)
{
return 1;
}

if (temp->left != NULL)
{
queue[++rear] = temp->left;
}

if (temp->right != NULL)
{
queue[++rear] = temp->right;
}
}
return -1;
}

int height(struct TreeNode* root)


{
if (root == NULL)
{
return 0;
}

int left = height(root->left);


int right = height(root->right);

if(left > right)


{
return left + 1;
}
else
{
return right + 1;
}
}

void inorder(struct TreeNode* root)


{
if(root == NULL) return;

inorder(root->left);
59
printf("%d ", root->val);
inorder(root->right);
}

void preorder(struct TreeNode* root)


{
if(root == NULL) return;

printf("%d ", root->val);


preorder(root->left);
preorder(root->right);
}

void postorder(struct TreeNode* root)


{
if(root == NULL) return;

postorder(root->left);
postorder(root->right);
printf("%d ", root->val);
}

void levelorder()
{
if (root == NULL)
{
printf("Tree is Empty!");
return;
}

struct TreeNode* queue[MAX_SIZE];


int front = -1;
int rear = -1;

queue[front + 1] = root;
front = rear = 0;

while (front <= rear)


{
struct TreeNode* temp = queue[front];
front++;

printf("%d ", temp->val);

if (temp->left != NULL)
{
queue[++rear] = temp->left;
60
}

if (temp->right != NULL)
{
queue[++rear] = temp->right;
}
}
}
Output:
--- Binary Tree --

1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
7. Postorder Traversal
8. Level order Traversal
9. Exit

Enter Your Choice: 1

Enter data for new node: 2

* Node with data 2 was inserted


Do u want to continue:::y

--- Binary Tree --

1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
7. Postorder Traversal
8. Level order Traversal
9. Exit

Enter Your Choice: 1

Enter data for new node: 4

* Node with data 4 was inserted


Do u want to continue:::y

61
--- Binary Tree --

1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
7. Postorder Traversal
8. Level order Traversal
9. Exit

Enter Your Choice: 3

Enter node data: 4

Node was found


Do u want to continue:::y

--- Binary Tree --

1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
7. Postorder Traversal
8. Level order Traversal
9. Exit

Enter Your Choice: 4

height of the tree is: 2


Do u want to continue:::y

--- Binary Tree --

1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
62
7. Postorder Traversal
8. Level order Traversal
9. Exit

Enter Your Choice: 1

Enter data for new node: 3

* Node with data 3 was inserted


Do u want to continue:::y

--- Binary Tree --

1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
7. Postorder Traversal
8. Level order Traversal
9. Exit

Enter Your Choice:


1

Enter data for new node: 7

* Node with data 7 was inserted


Do u want to continue:::y

--- Binary Tree --


1. Insert
2. Delete
3. Search
4. Height
5. Inorder Traversal
6. Preorder Traversal
7. Postorder Traversal
8. Level order Traversal
9. Exit

Enter Your Choice: 5

Inorder Traversal

7423
Do u want to continue:::
63
Ex. no.: 7 Tree Traversal - inorder, preorder and postorder

AIM:

To write a c program to implement Tree Traversal

ALGORITHM:-

Pre-order Traversal:
Visit the root node.
 Recursively traverse left sub-tree(in pre-order).
 Recursively traverse right sub-tree(in pre-order).
void preorder(Treenode T) {
if (T == NULL)
return;
printData(T->data);
preorder(T->left);
preorder(T->right);
return;
}

Post Order Traversal:

 Recursively traverse left subtree(in post order).


 Recursively traverse right subtree(in post order).
 Visit the root node.
Algorithm for Post order tree traversal:
void postorder(Treenode T) {
if (T == NULL)
return;
postorder(T->left);
postorder(T->right);
printData(T->data);
return;
}
Inorder Traversal:

 Recursively traverse left subtree(inorder).


 Visit the root node.
 Recursively traverse right subtree(inorder).
Algorithm for Inorder tree traversal:
void inorder(Treenode T) {
if (T == NULL)
return;
inorder(T->left);
64
printData(T->data);
inorder(T->right);
return;
}

PROGRAM:-

#include <stdio.h>
#include <stdlib.h>

struct tnode {
int data;
struct tnode *left, *right;
};
struct tnode *root = NULL;
struct tnode * createNode(int data) {
struct tnode *newNode;
newNode = (struct tnode *) malloc(sizeof(struct tnode));
newNode->data = data;
newNode->left = NULL;
newNode->right = NULL;
return (newNode);
}

void insertion(struct tnode **node, int data) {


if (!*node) {
*node = createNode(data);
} else if (data < (*node)->data) {
insertion(&(*node)->left, data);
} else if (data > (*node)->data) {
insertion(&(*node)->right, data);
}
}

void postOrder(struct tnode *node) {


if (node) {
postOrder(node->left);
postOrder(node->right);
printf("%d ", node->data);
}
return;
}

void preOrder(struct tnode *node) {


if (node) {
printf("%d ", node->data);
preOrder(node->left);
preOrder(node->right);

65
}
return;
}
void inOrder(struct tnode *node) {
if (node) {
inOrder(node->left);
printf("%d ", node->data);
inOrder(node->right);
}
return;
}
int main() {
int data, ch;
while (1) {
printf("\n1. Insertion\n2. Pre-order\n");
printf("3. Post-order\n4. In-order\n");
printf("5. Exit\nEnter your choice:");
scanf("%d", &ch);
switch (ch) {
case 1:
printf("Enter ur data:");
scanf("%d", &data);
insertion(&root, data);
break;
case 2:
preOrder(root);
break;
case 3:
postOrder(root);
break;
case 4:
inOrder(root);
break;
case 5:
exit(0);
default:
printf("U've entered wrong opetion\n");
break;
} }
return 0; }
Output
1. Insertion
2. Pre-order
3. Post-order
4. In-order
5. Exit
Enter your choice:1
Enter ur data:40
1. Insertion
2. Pre-order
66
3. Post-order
4. In-order
5. Exit
Enter your choice:2
20 15 8 10 30 25 40
1. Insertion
2. Pre-order
3. Post-order
4. In-order
5. Exit
Enter your choice:3
10 8 15 25 40 30 20
1. Insertion
2. Pre-order
3. Post-order
4. In-order
5. Exit
Enter your choice:4
8 10 15 20 25 30 40
1. Insertion
2. Pre-order
3. Post-order
4. In-order
5. Exit

RESULT :-

Thus the program has been successfully executed and


verified .

67
Ex. no.: 8.a Breadth First Search

AIM:

To write a c program to implement Breadth first search

ALGORITHM:

Step 1: Define a Queue of size total number of vertices in the graph.


Step 2: Select any vertex as starting point for traversal. Visit that vertex
and insert it into the Queue.
Step 3: Visit all the adjacent vertices of the vertex which is at front of the
Queue which is not visited and insert them into the Queue.
Step 4: When there is no new vertex to be visit from the vertex at front of
the Queue then delete that vertex from the Queue.
Step 5: Repeat step 3 and 4 until queue becomes empty.
Step 6: When queue becomes Empty, then produce final spanning tree by
removing unused edges from the graph

Program:

include<stdio.h>

int queue[10];

int front=0,back=0;

void push(int var)


{
queue[back] = var;
back++;
}

void pop()
{
queue[front] = 0;
front++;
}

int visited[7] = {0};

int main()
68
{
int v,n,i,j;

int graph[10][10];
printf("Enter the number of vertices: ");
scanf("%d", &n);
printf("Enter graph data in matrix form: \n");
for (i = 0; i < n; i++)
for (j = 0; j < n; j++)
scanf("%d", &graph[i][j]);

printf("Enter the starting vertex: ");


scanf("%d", &v);
push(v);
while(front != back)
{
int current = queue[front];

printf("%d ", current);

pop();

for(int i=0;i < 6;i++)


{
if((graph[current-1][i] == 1) && (visited[i] == 0))
{
visited[i] = 1; // marking visisted
push(i+1);
}
}
}
return 0;
}

OUTPUT
Enter the number of vertices: 6
Enter graph data in matrix form:
011000
101000
110110
001000
001001
000010
Enter the starting vertex: 2
2132456
RESULT:
Thus the above c program for Graph Traversal Algorithm is
successfully completed

69
Ex. no.: 8.b Depth First search

AIM:

To write a c program to implement Depth First search.

ALGORITHM:

1. First, create a stack with the total number of vertices in the graph.
2. Now, choose any vertex as the starting point of traversal, and push
that vertex into the stack.

3. After that, push a non-visited vertex (adjacent to the vertex on the


top of the stack) to the top of the stack.

4. Now, repeat steps 3 and 4 until no vertices are left to visit from the
vertex on the stack's top.

5. If no vertex is left, go back and pop a vertex from the stack.

6. Repeat steps 2, 3, and 4 until the stack is empty.

PROGRAM:

#include <stdio.h>

int a[20][20], visited[20], n;

void dfs(int v)

int i;

visited[v] = 1;

for (i = 1; i <= n; i++)

if (a[v][i] && !visited[i])

printf("\n %d->%d", v, i);

dfs(i);

}
70
}

int main( )

int i, j,v, count = 0;

printf("\n Enter number of vertices:");

scanf("%d", &n);

for (i = 1; i <= n; i++)

visited[i] = 0;

for (j = 1; j <= n; j++)

a[i][j] = 0;

printf("\n Enter the adjacency matrix:\n");

for (i = 1; i <= n; i++)

for (j = 1; j <= n; j++)

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

printf("Enter the starting vertex: ");

scanf("%d", &v);

dfs(v);

return 0;

OUTPUT

Enter number of vertices:6

Enter the adjacency matrix:

71
011000

101000

110110

001000

001001

000010

Enter the starting vertex: 2

2->1

1->3

3->4

3->5

5->6

72
Ex. no.:9.a Prim’s Algorithm

AIM:

To write a c program to implement Prim’s Algorithm

ALGORITHM:

1. Declare an array visited[] to store the visited vertices and firstly, add
the arbitrary root, say S, to the visited array.

2. Check whether the adjacent vertices of the last visited vertex are
present in the visited[] array or not.

3. If the vertices are not in the visited[] array, compare the cost of edges
and add the least cost edge to the output spanning tree.

4. The adjacent unvisited vertex with the least cost edge is added into the
visited[] array and the least cost edge is added to the minimum
spanning tree output.

5. Steps 2 and 4 are repeated for all the unvisited vertices in the graph to
obtain the full minimum spanning tree output for the given graph.

6. Calculate the cost of the minimum spanning tree obtained.


Program:

# include<stdio.h>
int G[50][50],select[50], i, j, k, n, min_dist,total=0,u, v;
void Prim()
{
printf("\n\n The Minimal Spanning Tree Is :\n");
select[0] = 1;
for (k=1 ; k<n ; k++)
{
min_dist = 32767;
for (i=0 ; i<n ; i++)
for (j=0 ; j<n ; j++)
if (G[i][j] && ((select[i] && !select[j]) || (!select[i] && select[j])))
if (G[i][j] < min_dist)
{
min_dist = G[i][j];
u = i;
v = j;
}
printf("\n Edge (%d %d )and weight = %d",u,v,min_dist);
select[u] = select[v] = 1;
total =total+min_dist;
73
}
printf("\n\n\t Total Path Length Is = %d",total);
}

int main()
{
printf("\n Enter Number of Nodes in The Graph: ");
scanf("%d",&n);
for(i=0;i<n;i++)
{ printf("\n");
for(j=0;j<n;j++)
{
printf("a[%d][%d]: ",i,j);
scanf("%d",&G[i][j]);
}
}
Prim();
return 0;
}

Output:-
Enter Number of Nodes in The Graph: 6

a[0][0]: 0
a[0][1]: 3
a[0][2]: 1
a[0][3]: 6
a[0][4]: 0
a[0][5]: 0

a[1][0]: 3
a[1][1]: 0
a[1][2]: 5
a[1][3]: 0
a[1][4]: 3
a[1][5]: 0

a[2][0]: 1
a[2][1]: 5
a[2][2]: 0
a[2][3]: 5
a[2][4]: 6
a[2][5]: 4

a[3][0]: 6
a[3][1]: 0
a[3][2]: 5
a[3][3]: 0
a[3][4]: 0
a[3][5]: 2
74
a[4][0]: 0
a[4][1]: 3
a[4][2]: 6
a[4][3]: 0
a[4][4]: 0
a[4][5]: 6

a[5][0]: 0
a[5][1]: 0
a[5][2]: 4
a[5][3]: 2
a[5][4]: 6
a[5][5]: 0

The Minimal Spanning Tree Is :

Edge (0 2 )and weight = 1


Edge (0 1 )and weight = 3
Edge (1 4 )and weight = 3
Edge (2 5 )and weight = 4
Edge (3 5 )and weight = 2

Total Path Length Is = 13


--------------------------------

RESULT:
Thus the above c program of Prim’s Algorithm implementation is
successfully completed.

75
Ex. no.:9.b Kruskal’s Algorithm

AIM:

To write a c program to implement Kruskal’s Algorithm

ALGORITHM:

1. Sort all the edges in the graph in an ascending order and store it in
an array edge[].

2. Construct the forest of the graph on a plane with all the vertices in
it.

3. Select the least cost edge from the edge[] array and add it into the
forest of the graph. Mark the vertices visited by adding them into
the visited[] array.

4. Repeat the steps 2 and 3 until all the vertices are visited without
having any cycles forming in the graph

5. When all the vertices are visited, the minimum spanning tree is
formed.

6. Calculate the minimum cost of the output spanning tree formed.


PROGRAM

#include <stdio.h>

#include <stdlib.h>

const int inf = 999999;

int k, a, b, u, v, n, ne = 1;

int mincost = 0;

int cost[3][3] = {{0, 10, 20},{12, 0,15},{16, 18, 0}};

int p[9] = {0};

int applyfind(int i)

while(p[i] != 0)

i=p[i];

return i;
76
}

int applyunion(int i,int j)

if(i!=j) {

p[j]=i;

return 1;

return 0;

int main()

n = 3;

int i, j;

for (int i = 0; i < n; i++) {

for (int j = 0; j < n; j++) {

if (cost[i][j] == 0) {

cost[i][j] = inf;

printf("Minimum Cost Spanning Tree: \n");

while(ne < n) {

int min_val = inf;

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

for(j=0; j <n; j++) {

if(cost[i][j] < min_val) {

min_val = cost[i][j];

77
a = u = i;

b = v = j;

u = applyfind(u);

v = applyfind(v);

if(applyunion(u, v) != 0) {

printf("%d -> %d\n", a, b);

mincost +=min_val;

cost[a][b] = cost[b][a] = 999;

ne++;

printf("Minimum cost = %d",mincost);

return 0;

Output

Minimum Cost Spanning Tree:

0 -> 1

1 -> 2

Minimum cost = 25

Ex. no.:10 Dijkstra’s algorithm

78
AIM:

To write a c program to implement Dijkstra’s algorithm

Algorithm:

1. Mark the source node with a current distance of 0 and the rest with
infinity.

2. Set the non-visited node with the smallest current distance as the
current node.

3. For each neighbor, N of the current node adds the current distance
of the adjacent node with the weight of the edge connecting 0->1. If
it is smaller than the current distance of Node, set it as the new
current distance of N.

4. Mark the current node 1 as visited.

5. Go to step 2 if there are any nodes are unvisited.

PROGRAM:
#include <stdio.h>
#include <limits.h>

#define MAX_VERTICES 100

int minDistance(int dist[], int sptSet[], int vertices) {


int min = INT_MAX, minIndex;

for (int v = 0; v < vertices; v++) {


if (!sptSet[v] && dist[v] < min) {
min = dist[v];
minIndex = v;
}
}

return minIndex;
}

void printSolution(int dist[], int vertices)


{
printf("Vertex \tDistance from Source\n");
for (int i = 0; i < vertices; i++) {
printf("%d \t%d\n", i, dist[i]);
}
}

79
void dijkstra(int graph[MAX_VERTICES][MAX_VERTICES], int src, int
vertices)
{
int dist[MAX_VERTICES];
int sptSet[MAX_VERTICES];

for (int i = 0; i < vertices; i++) {


dist[i] = INT_MAX;
sptSet[i] = 0;
}

dist[src] = 0;

for (int count = 0; count < vertices - 1; count++) {

int u = minDistance(dist, sptSet, vertices);

sptSet[u] = 1;

for (int v = 0; v < vertices; v++) {

if (!sptSet[v] && graph[u][v] && dist[u] != INT_MAX && dist[u] +


graph[u][v] < dist[v]) {
dist[v] = dist[u] + graph[u][v];
}
}
}

printSolution(dist, vertices);
}

int main() {
int vertices;

printf("Input the number of vertices: ");


scanf("%d", &vertices);

if (vertices <= 0 || vertices > MAX_VERTICES) {


printf("Invalid number of vertices. Exiting...\n");
return 1;
}

80
int graph[MAX_VERTICES][MAX_VERTICES];

printf("Input the adjacency matrix for the graph (use INT_MAX for
infinity):\n");
for (int i = 0; i < vertices; i++) {
for (int j = 0; j < vertices; j++) {
scanf("%d", &graph[i][j]);
}
}

int source;

printf("Input the source vertex: ");


scanf("%d", &source);

if (source < 0 || source >= vertices) {


printf("Invalid source vertex. Exiting...\n");
return 1;
}

dijkstra(graph, source, vertices);

return 0;
}

Output:
Input the number of vertices: 5
Input the adjacency matrix for the graph (use INT_MAX for infinity):
03200
30010
20014
01102
00420
Input the source vertex: 0
Vertex Distance from Source
0 0
1 3
2 2
3 3
4 5

Ex. no.: 11 a QUICK SORT

81
AIM:-
To arrange the list of numbers in ascending order using quick
sort

ALGORITHM:-

STEP 1: Start the program


STEP 2:Enter the limit of an array n
STEP 3: Insert the elements one by one up to n value
STEP 4:Pick one element in the array, which will be the pivot.
STEP 5: Make one pass through the array, called a partition
step, re-arranging the entries so that:
the pivot is in its proper place and entries smaller than the pivot are
to the left of the pivot and entries larger than the pivot are to its
right.
STEP 6: Recursively apply quick sort to the part of the array that
is to the left of the pivot, and to the right part of the
array.
STEP 7: Stop the program

PROGRAM:

#include<stdio.h>
#include<conio.h>
void quicksort(int [10],int,int);
void main()
{
int a[20],n,i;
clrscr();
printf("Enter size of the array: ");
scanf("%d",&n);
printf("Enter elements: ");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
quicksort(a,0,n-1);
printf("Sorted elements: ");
for(i=0;i<n;i++)
printf(" %d",a[i]);
getch();
}

void quicksort(int a[10],int first,int last)


{
int pivot,j,temp,i;
if(first<last)
{
pivot=first;
i=first;
j=last;
while(i<j)
82
{
while(a[i]<=a[pivot]&&i<last)
i++;
while(a[j]>a[pivot])
j--;
if(i<j){
temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
temp=a[pivot];
a[pivot]=a[j];
a[j]=temp;
quicksort(a,first,j-1);
quicksort(a,j+1,last);
}
}

OUTPUT:
Enter size of array: 5
Enter Elements: 6 2 9 8 4
Sorted Elements: 2 4 6 8 9

RESULT:-

Thus the program has been successfully executed and verified

83
Ex. no.: 11b MERGE SORT

AIM:-
To arrange the list of numbers in ascending order using Merge
sort

ALGORITHM:-
STEP 1 : Divide Step If a given array A has zero or one element, simply
return; it is already sorted. Otherwise, split A[p .. r] into two subarrays A[p
.. q] and A[q + 1 .. r], each containing about half of the elements of A[p ..
r]. That is, q is the halfway point of A[p .. r].

STEP 2 : Conquer Step Conquer by recursively sorting the two subarrays


A[p .. q] and A[q + 1 .. r].

STEP 3 :Combine Step Combine the elements back in A[p .. r] by merging


the two sorted subarrays A[p .. q] and A[q + 1 .. r] into a sorted sequence.
To accomplish this step, we will define a procedure MERGE (A, p, q, r).

PROGRAM:

#include<stdio.h>
#include<conio.h>

void merge_split(int a[],int first,int last);


void merge(int a[],int f1,int l1,int f2,int l2);
int a[25],b[25];

void main()
{
int i,n;
clrscr();
printf("\n\nMERGE SORT");
printf("\n\n*********");
printf("\n\nEnter the limit : ");
scanf("%d",&n);
printf("\nEnter the elements\n");
for(i=0;i<n;i++)
scanf("%d",&a[i]);
merge_split(a,0,n-1);
printf("\n\nSorted list : ");
for(i=0;i<n;i++)
printf("\n %d",a[i]);
getch();
}

void merge_split(int a[],int first,int last)


{
int mid;
84
if(first<last)
{
mid=(first+last)/2;
merge_split(a,first,mid);
merge_split(a,mid+1,last);
merge(a,first,mid,mid+1,last);
}
}

void merge(int a[],int f1,int l1,int f2,int l2)


{
int i,j,k=0;
i=f1;
j=f2;
while(i<=l1 && j<=l2)
{
if(a[i]<a[j])
b[k]=a[i++];
else
b[k]=a[j++];
k++;
}
while(i<=l1)
b[k++]=a[i++];
while(j<=l2)
b[k++]=a[j++];
i=f1;
j=0;
while(i<=l2 && j<k)
a[i++]=b[j++];
}

SAMPLE INPUT AND OUTPUT:

Enter the limit : 5


Enter the elements
54321
Sorted list:
1
2
3
4
5

RESULT:-

Thus the program has been successfully executed and verified .

85
Ex. no.: 12 a LINEAR SEARCH

AIM:-
To write a c program to implement linear search

ALGORITHM:-

STEP 1
:Start the program
STEP 2
:Enter the limit to n
STEP 3
:Read the values in an array upto n
STEP 4
:Enter the element m to be searched in an array
STEP 5
:Find whether the element is found in the list of values
STEP 6
:If it is present, then assign a flag.
STEP 7
:If the value of flag is 1,then print that the element is found
in the list of elements.
STEP 8 :Else the element is not found
STEP 9 :Stop the program.

PROGRAM:

#include <stdio.h>
#include<conio.h>
void main()
{
int a[100], search, i, n;
clrscr();
printf("Enter the number of elements in array\n");
scanf("%d",&n);
printf("Enter elements:");
for (i = 0; i < n; i++)
scanf("%d", &a[i]);

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


scanf("%d", &search);

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


{
if (a[i] == search) /* if required element found */
{
printf("%d is present at location %d.\n", search, i+1);
break;
}
}
if (i == n)
printf("%d is not present in array.\n", search);

getch();
}
86
OUTPUT:
Enter the number of elements in array: 5
Enter elements
67
23
45
89
1
Enter the number to search: 23
23 is present at location 2

RESULT :-

Thus the program has been successfully executed and


verified .

87
Ex. no.: 12 b BINARY SEARCH

AIM:-
To write a c program to implement binary search

ALGORITHM:-

STEP 1 : Start the program


STEP 2 : Enter the limit to n
STEP 3 : Read the values which is sorted in an array upto n
STEP 4 : Enter the element to be searched in an array
STEP 5 : Find the first and last position from the list of values
STEP 6 : Now find the middle value using the formula,
Mid=(first+last)/2
STEP 7 : If the value search is equal to the mid position, then
assign a flag.
STEP 8 : Else if the value is greater than the mid position, search
the element in the right half.
STEP 9 : Else search the element in the left half.
STEP 10 : If the flag is assigned as 1,then the element is found in
the list of values.
STEP 11 : Else the element is not found
STEP 12 : Stop the program.

PROGRAM:
#include <stdio.h>
#include<conio.h>
void main()
{
int i, first, last, middle, n, search, a[100];
clrscr();
printf("Enter number of elements\n");
scanf("%d",&n);

printf("Enter Elements:");

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


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

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


scanf("%d",&search);

first = 0;
last = n - 1;
middle = (first+last)/2;

while( first <= last )


{
88
if ( a[middle] < search )
first = middle + 1;
else if ( a[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 is not present in the list.\n", search);

getch();
}

OUTPUT:
Enter the number of elements in array: 5
Enter elements
1 2 3 4 5
Enter value to find: 3
3 found at location 3

RESULT : -

Thus the program has been successfully executed and


verified .

89

You might also like