Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
38 views63 pages

LDS Lab Manual

The document is a lab manual for Linear Data Structures at Bharati Vidyapeeth College of Engineering, Pune, outlining the vision and mission of the institute and department, along with general instructions for laboratory conduct. It details the objectives of the lab, weekly experiment plans, examination and marking schemes, and the necessary software and hardware requirements. Additionally, it includes educational objectives, outcomes, and a list of experiments focused on implementing various data structures and algorithms using C programming.

Uploaded by

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

LDS Lab Manual

The document is a lab manual for Linear Data Structures at Bharati Vidyapeeth College of Engineering, Pune, outlining the vision and mission of the institute and department, along with general instructions for laboratory conduct. It details the objectives of the lab, weekly experiment plans, examination and marking schemes, and the necessary software and hardware requirements. Additionally, it includes educational objectives, outcomes, and a list of experiments focused on implementing various data structures and algorithms using C programming.

Uploaded by

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

BHARATI VIDYAPEETH

(DEEMED TO BE UNIVERSITY)
COLLEGE OF ENGINEERING, PUNE

Lab Manual
LINEAR DATA STRUCTURES

Computer Science and Engineering

Lab Manual: Linear Data Structures 1


Vision of the Institute
To be World Class Institute for Social Transformation Through Dynamic Education.

Mission of the Institute


1. To provide quality technical education with advanced equipments, qualified faculty members,
infrastructure to meet needs of profession and society.

2. To provide an environment conductive to innovation, creativity, research and entrepreneurial


leadership.

3. To practice and promote professional ethics, transparency and accountability for social community,
economic and environmental conditions.

VISION OF THE DEPARTMENT

To be focused on innovative and quality education in computer science and engineering that
prepares professionals for development of society.

MISSION OF THE DEPARTMENT

 To provide academic environment for the development of skilled professionals


 To cultivate research culture that contributes to the sustainable development of the
society.
 To enhance academic and industry collaborations for global exposure.

General Instructions (Laboratory rules/ Practical oriented rules)


 Equipment in the lab is meant for the use of students. Students need to maintain a proper decorum in
the computer lab. Students must use the equipment with care.
 Students are required to carry their reference materials, files and records with completed assignment
while entering the lab.
 Students are supposed to occupy the systems allotted to them and are not supposed to talk or make
noise in the lab.
 All the students should perform the given assignment individually.

Lab Manual: Linear Data Structures 2


 Lab can be used in free time/lunch hours by the students who need to use the systems should take
prior permission from the lab in-charge.
 All the Students are instructed to carry their identity cards when entering the lab.
 Lab files need to be submitted on or before date of submission.
 Students are not supposed to use pen drives, compact drives or any other storage devices in the lab.
 For Laboratory related updates and assignments students should refer to the notice board in the Lab

General Information (Course Oriented)

C Programming is an ANSI/ISO standard and powerful programming language for developing real-time
applications. C programming language was invented by Dennis Ritchie at the Bell Laboratories in 1972. It
was invented for implementing UNIX operating system. C is most widely used programming language
even today. All other programming languages were derived directly or indirectly from C programming
concepts.

Objectives of the lab


The course introduces fundamental concepts of data structureS

1. Understand the fundamentals and analysis of algorithms

2. Implement Linear data structures

3. Implement the searching algorithms

4. Implement the sorting algorithms

5. Understand the concepts of different file system organization

Lab Manual: Linear Data Structures 3


Weekly Plan

Lab Manual: Linear Data Structures 4


Sr. Experiment Name Planned
No. Week

1 Write a program for following Array Operations: 1st Week


2nd Week
 Insertion 3rd Week

 Deletion

 Traversal.

2 Write a program for Linked List Implementation: 4th Week


5th Week
 Singly Linked Lists

 Doubly Linked Lists

 Circular Linked Lists.

Experiment: Measure the time taken for insertion at various positions.

3 Write a program for Stack and Queue Implementation:


6th Week
 Stack Implementation using arrays and linked lists. 7th Week

4 Write a program for Stack and Queue Implementation: 8th Week


9th Week
 Queue Implementation using arrays and linked lists.

Experiment: Compare performance of stack vs. queue for different


operations (push, pop, enqueue, dequeue).

5 Write a program for Implementation of Array Operations: 10th Week


11th Week
 Searching (Linear Search).

 Searching ( Binary Search).

Experiment: Compare time complexity of linear vs. binary search.

6 Write a program for Implementation of following Sorting Algorithms: 12th Week


13th Week
 Bubble Sort

 Merge Sort

 Quick Sort Lab Manual: Linear Data Structures 5


Experiment: Compare the efficiency of different sorting techniques with
varying input sizes.

7 Write a program for Implementation direct access file 14th Week


Conduction Time: 2 Hrs Per week

Examination Scheme
Practical Exam is conducted at the end of semester.

Marking Scheme
Practical: 01 Credit

Term Work and Practical: 25 Marks

Laboratory Usage

Laboratory of data structures and algorithms consist of 20 machines with following configuration.

Software Requirements
System configuration:

2GB of RAM,

Win 10, NT server, Win 2K server, IIS 5.0,

Visual Studio Code or TurboC++

Practical Pre-requisite
Students should have knowledge of Fundamentals of data types and programming concepts.

Program Educational Objectives

The students of B.TECH. (Computer Science and Engineering), after graduating will able to,

1. Demonstrate technical and professional competencies by applying Engineering


Fundamentals, knowledge of computing and technologies.
2. Exhibit effective personality, good communication and team building skills
3. Adopt to the latest trends in the field of computer science and engineering.
Program Outcomes

1. Apply the knowledge of mathematics, science, engineering, and computing to provide a


solution of complex engineering problems.

Lab Manual: Linear Data Structures 6


2. Identify, analyse complex engineering problems to derive conclusions using computer
science and engineering knowledge.
3. Outline resolutions for complex engineering problems and design system components
or processes that meet the specified needs with appropriate consideration, societal, and
environmental considerations.
4. Use existing research knowledge and research techniques including design of
experiments, data analysis, and synthesis to provide valid inferences.
5. Create, select, and apply appropriate techniques, resources, and modern engineering
and IT tools.
6. Apply inferences obtained by the contextual knowledge to assess societal, health,
safety, legal, and cultural issues and the subsequent responsibilities relevant to the
professional engineering practice.
7. Recognize the impact of the professional engineering solutions in societal and
environmental contexts to demonstrate the knowledge for sustainable development.
8. Apply ethical principles and execute professional ethics and responsibilities and norms
of the engineering practice.
9. Work effectively as an individual, and as a member or leader in diverse teams, and in
multidisciplinary surroundings.
10.Talk effectively on complex engineering activities with the engineering community
such as being able to comprehend and write effective reports and design
documentation, make effective presentations.
11.Prove knowledge and understanding of the engineering and management principles and
apply these to one’s work, as a member and leader in a team.
12.Recognise the need for and have the preparation and ability to engage in independent
and life-long learning in context of technological change.
Course Outcomes

Lab Manual: Linear Data Structures 7


1. Understand the fundamentals and analysis of algorithms

2. Implement Linear data structures

3. Implement Non-Linear data structure of Trees.

4. Implement Non-Linear data structure of Graphs.

5. Implement the sorting algorithms

6. Understand the concepts of different file system organisation

CO-PO mapping

PO  a b c d e f g h i j k l
CO1 2 2 1

CO2 1 2 2

CO3 2 1 2

CO4 2 2 1

CO5 2 1 2 1

CO6 2 2 1 2

How outcomes are assessed?

Lab Manual: Linear Data Structures 8


Assignment
Outcome Level Proficiency evaluated by
Number

Understand the
fundamentals and analysis
of algorithms

Performing Practical and


1 3,2
reporting results

Problem definition
Implement Linear data
2,3,4 1,2,2,3 &Performing Practical and
structures
reporting results

Implement the searching Performing experiments


5,6 3
sorting algorithms and reporting results

Understand the concepts of Performing experiments


different file system 7 2,2
and reporting results
organisation

Learning Experience Gained

The students learn both soft skills and technical skills while they are undergoing the practical sessions.
The soft skills gained in terms of communication, presentation and behavior. While technical skills they
gained in terms of C programming .

Bharati Vidyapeeth Deemed To Be University


College of Engineering, Pune
Computer Science and Engineering
Academic Year 2024-2025
B. Tech. CSE (SEM II)
List of Experiments
Lab Manual: Linear Data Structures 9
Subject: LINEAR DATA STRUCTURES

Lab Manual: Linear Data Structures 10


Sr. Experiment Name Planned
No. Week

1 Write a program for following Array Operations: 1st Week


2nd Week
 Insertion
Experiment No: 1
 Deletion
Write a program for following Array Operations:
 Traversal.
2 Insertion
Write a program for Linked List Implementation: 3rd Week

 Deletion
 Singly Linked Lists

 Doubly Linked Lists


 Traversal.
 Circular Linked Lists.
Objective:
Experiment:
To implement Measure the
and understand timeoperations
basic taken for insertion at various
on arrays, positions.
including insertion, deletion, and traversal,
along with their respective algorithms.
3 Write a program for Stack and Queue Implementation: 4th Week
Array:
An array  Stack Implementation
is a linear usingstores
data structure that arrayselements
and linked
inlists.
contiguous memory locations. Array
operations such as insertion, deletion, and traversal are fundamental to data structure manipulation.
 Queue Implementation using arrays and linked lists.
1. Traversal: Accessing and displaying each element of the array sequentially.
Experiment:
2. Insertion: Compare
Adding a newperformance
element at aofspecified
stack vs. position,
queue forrequiring
different a shift of elements if
operations (push, pop, enqueue, dequeue).
necessary.
4 3. Deletion:
Write CRemoving
programs that use recursive
an element fromfunctions to traverse
a specified position,the given binary
requiring
th
elements5toWeek
shift to fill the
tree
gap. in

 Preorder

 Inorder and
Algorithm:
 Postorder
1. Traversal
The process of accessing and displaying all elements in the array.Algorithm: Traverse(array, n)
5 1. Start
Write a program for Implementation of following Graph Algorithms:
2. For i=0 to n−1 do: 6th Week
 BFS Algorithms. 7th Week
Print array[i]
 DFS Algorithms.
3. End
Experiment: Implement shortest path algorithms and measure execution
time.

2.6 Insertion
Write a program for Implementation of Array Operations:
8th Week
 Searching (Linear Search). 9th Week 11
Lab Manual: Linear Data Structures
 Searching ( Binary Search).

Experiment: Compare time complexity of linear vs. binary search.

7 Write a program for Implementation of following Sorting Algorithms:


10th Week
Inserting an element at a specified position involves shifting elements from that position to the right.
Algorithm: Insert(array, n, position, value)
1. Start
2. If position<0nor position>n:

Print "Invalid Position" and exit.


3. For i=n−1i = n-1i=n−1 to position, do:

array[i+1]=array[i]
4. Set array[position]=valuearray[position]
5. Increment n.

6. End

3. Deletion
Deleting an element from a specified position involves shifting elements to the left to fill the gap.
Algorithm: Delete(array, n, position)
1. Start
2. If position<0 or position≥n:

Print "Invalid Position" and exit.


3. For i=positioni = positioni=position to n−2 do:

array[i]=array[i+1]
4. Decrement n.
5. End

Time complexity-
 Traversal: O(n)
 Insertion: O(n)in the worst case.

 Deletion: O(n)in the worst case.

Lab Manual: Linear Data Structures 12


Program:
#include <stdio.h>
// Function to traverse the array
void traverse(int arr[], int n) {
printf("Array Elements: ");
for (int i = 0; i < n; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Function to insert an element into the array
void insert(int arr[], int *n, int position, int value) {
if (position < 0 || position > *n) {
printf("Invalid Position\n");
return;
}
for (int i = *n - 1; i >= position; i--) {
arr[i + 1] = arr[i];
}
arr[position] = value;
(*n)++;
}
// Function to delete an element from the array
void deleteElement(int arr[], int *n, int position) {
if (position < 0 || position >= *n) {
printf("Invalid Position\n");
return;
}
for (int i = position; i < *n - 1; i++) {
arr[i] = arr[i + 1];

Lab Manual: Linear Data Structures 13


}
(*n)--;
}
// Main function
int main() {
int arr[100], n = 5;

// Initial array
arr[0] = 1; arr[1] = 2; arr[2] = 3; arr[3] = 4; arr[4] = 5;
// Traverse the array
printf("Original Array:\n");
traverse(arr, n);
// Insert an element at position 2
printf("Inserting 99 at position 2:\n");
insert(arr, &n, 2, 99);
traverse(arr, n);
// Delete an element at position 3
printf("Deleting element at position 3:\n");
deleteElement(arr, &n, 3);
traverse(arr, n);
return 0;
}
Questions:

1. How do you insert an element into an array at a specific position?

2. How do you delete an element from an array?

3. What are the limitations of arrays in terms of memory allocation?

4. How do you find the minimum and maximum values in an array?

Lab Manual: Linear Data Structures 14


Experiment No: 2
Write a program for Linked List Implementation:
 Singly Linked Lists
 Doubly Linked Lists
 Circular Linked Lists.
Linked List :

When we want to work with an unknown number of data values, we use a linked list data structure to

organize that data. The linked list is a linear data structure that contains a sequence of elements such

that each element links to its next element in the sequence. Each element in a linked list is called

"Node". Linked List can be implemented as 1. Singly Linked List 2. Doubly Linked List 3. Circular

Linked List Single Linked List Simply a list is a sequence of data, and the linked list is a sequence of

data linked with each other. The formal definition of a single linked list is as follows... In any single

linked list, the individual element is called as "Node". Every "Node" contains two fields, data field, and

the next field. The data field is used to store actual value of the node and next field is used to store the

address of next node in the sequence.

 Operations on Single Linked List,Doubly Linked Lists,Circular Linked Lists :

The following operations are performed on a Single Linked List ,Doubly Linked Lists,

Circular Linked Lists.

1. Creation

2. Insertion

Lab Manual: Linear Data Structures 15


3. Deletion

4. Display

 Singly Linked Lists


Before we implement actual operations, first we need to set up an empty list. First, perform the

following steps before implementing actual operations.

1.Creation

Step 1 - Define a Node structure with two members data and next

Step 2 - Define a Node pointer 'head' and set it to NULL.

2.Insertion

In a single linked list, the insertion operation can be performed in three ways. They are as

follows...

2.1 Inserting At Beginning of the list

2.2 Inserting At End of the list

2.3 Inserting At Specific location in the list

2.1 Inserting At Beginning of the list

We can use the following steps to insert a new node at beginning of the single linked list...

Step 1 - Create a newNode with given value.

Step 2 - Check whether list is Empty (head == NULL)

Step 3 - If it is Empty then, set newNode→next = NULL and head = newNode.

Step 4 - If it is Not Empty then, set newNode→next = head and head = newNode.

2.2 Inserting At End of the list

We can use the following steps to insert a new node at end of the single linked list...

Lab Manual: Linear Data Structures 16


Step 1 - Create a newNode with given value and newNode → next as NULL.

Step 2 - Check whether list is Empty (head == NULL).

Step 3 - If it is Empty then, set head = newNode.

Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.

Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list

(until temp → next is equal to NULL).

Step 6 - Set temp → next = newNode.

2.3 Inserting At Specific location in the list (After a Node)

We can use the following steps to insert a new node after a node in the single linked list...

Step 1 - Create a newNode with given value.

Step 2 - Check whether list is Empty (head == NULL)

Step 3 - If it is Empty then, set newNode → next = NULL and head = newNode.

Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.

Step 5 - Keep moving the temp to its next node until it reaches to the node after which

we want to insert the newNode (until temp1 → data is equal to location, here

location is the node value after which we want to insert the newNode).

Step 6 - Every time check whether temp is reached to last node or not. If it is reached to

last node then display 'Given node is not found in the list!!! Insertion not

possible!!!' and terminate the function. Otherwise move the temp to next node.

Step 7 - Finally, Set 'newNode → next = temp → next' and 'temp → next = newNode'

3. Deletion

In a single linked list, the deletion operation can be performed in three ways. They are as

Lab Manual: Linear Data Structures 17


follows...

3.1 Deleting from Beginning of the list

3.2 Deleting from End of the list

3.3 Deleting a Specific Node

3.1 Deleting from Beginning of the list

We can use the following steps to delete a node from beginning of the single linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and terminate

the function.

Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.

Step 4 - Check whether list is having only one node (temp → next == NULL)

Step 5 - If it is TRUE then set head = NULL and delete temp (Setting Empty list conditions)

Step 6 - If it is FALSE then set head = temp → next, and delete temp.

3.2 Deleting from End of the list

We can use the following steps to delete a node from end of the single linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and

terminate the function.

Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and

initialize 'temp1' with head.

Step 4 - Check whether list has only one Node (temp1 → next == NULL)

Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate the

Lab Manual: Linear Data Structures 18


function. (Setting Empty list condition)

Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node.

Repeat the same until it reaches to the last node in the list.

(until temp1 →next == NULL)

Step 7 - Finally, Set temp2 → next = NULL and delete temp1.

3.3 Deleting a Specific Node from the list

We can use the following steps to delete a specific node from the single linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and

terminate the function.

Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and

initialize 'temp1' with head.

Step 4 - Keep moving the temp1 until it reaches to the exact node to be deleted or to the

last node. And every time set 'temp2 = temp1' before moving the 'temp1' to its

next node.

Step 5 - If it is reached to the last node then display 'Given node not found in the list!

Deletion not possible!!!'. And terminate the function.

Step 6 - If it is reached to the exact node which we want to delete, then check whether list

is having only one node or not

Step 7 - If list has only one node and that is the node to be deleted, then

set head = NULL and delete temp1 (free(temp1)).

Step 8 - If list contains multiple nodes, then check whether temp1 is the first node in the

Lab Manual: Linear Data Structures 19


list (temp1 == head).

Step 9 - If temp1 is the first node then move the head to the next node (head = head →

next) and delete temp1.

Step 10 - If temp1 is not first node then check whether it is last node in the list

(temp1 → next == NULL).

Step 11 - If temp1 is last node then set temp2 → next = NULL and

delete temp1 (free(temp1)).

Step 12 - If temp1 is not first node and not last node then set temp2 → next = temp1 →

next and delete temp1 (free(temp1)).

4. Displaying a Single Linked List

We can use the following steps to display the elements of a single linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty then, display 'List is Empty!!!' and terminate the function.

Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.

Step 4 - Keep displaying temp → data with an arrow (--->) until temp reaches to the last

node

Step 5 - Finally display temp → data with arrow pointing to NULL (temp → data ---> NULL).

Double Linked List

Double linked list is a sequence of elements in which every element has links to its previous

element and next element in the sequence.

1.Creation

Step 1 - Define a Node structure with two members data and next

Lab Manual: Linear Data Structures 20


Step 2 - Define a Node pointer 'head' and set it to NULL.

2.Insertion

In a double linked list, the insertion operation can be performed in three ways as follows...

2.1 Inserting At Beginning of the list

2.2 Inserting At End of the list

2.3 Inserting At Specific location in the list

2.1 Inserting At Beginning of the list

We can use the following steps to insert a new node at beginning of the double linked list...

Step 1 - Create a newNode with given value and newNode → previous as NULL.

Step 2 - Check whether list is Empty (head == NULL)

Step 3 - If it is Empty then, assign NULL to newNode → next and newNode to head.

Step 4 - If it is not Empty then, assign head to newNode → next and newNode to head.

2.2 Inserting At End of the list

We can use the following steps to insert a new node at end of the double linked list...

Step 1 - Create a newNode with given value and newNode → next as NULL.

Step 2 - Check whether list is Empty (head == NULL)

Step 3 - If it is Empty, then assign NULL to newNode →

previous and newNode to head.

Step 4 - If it is not Empty, then, define a node pointer temp and initialize with head.

Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list

(until temp → next is equal to NULL).

Step 6 - Assign newNode to temp → next and temp to newNode → previous.

Lab Manual: Linear Data Structures 21


2.3 Inserting At Specific location in the list (After a Node)

We can use the following steps to insert a new node after a node in the double linked list...

Step 1 - Create a newNode with given value.

Step 2 - Check whether list is Empty (head == NULL)

Step 3 - If it is Empty then, assign NULL to both newNode → previous &

newNode → next and set newNode to head.

Step 4 - If it is not Empty then, define two node pointers temp1 & temp2 and

initialize temp1 with head.

Step 5 - Keep moving the temp1 to its next node until it reaches to the node after which

we want to insert the newNode (until temp1 → data is equal to location, here

location is the node value after which we want to insert the newNode).

Step 6 - Every time check whether temp1 is reached to the last node. If it is reached to

the last node then display 'Given node is not found in the list!!! Insertion not

possible!!!' and terminate the function. Otherwise move the temp1 to next node.

Step7- Assign temp1→next to temp2, newNode to temp1 → next,

temp1 to newNode → previous, temp2 to

newNode → nextand newNode to temp2 → previous.

3.Deletion

In a double linked list, the deletion operation can be performed in three ways as follows...

3.1 Deleting from Beginning of the list

3.2 Deleting from End of the list

3.3 Deleting a Specific Node

Lab Manual: Linear Data Structures 22


3.1 Deleting from Beginning of the list

We can use the following steps to delete a node from beginning of the double linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and

terminate the function.

Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize with head.

Step 4 - Check whether list is having only one node (temp → previous is equal to

temp → next)

Step 5 - If it is TRUE, then set head to NULL and delete temp (Setting Empty

list conditions)

Step 6 - If it is FALSE, then assign temp → next to head, NULL to

head → previous and delete temp.

3.2 Deleting from End of the list

We can use the following steps to delete a node from end of the double linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty, then display 'List is Empty!!! Deletion is not possible' and

terminate the function.

Step 3 - If it is not Empty then, define a Node pointer 'temp' and initialize with head.

Step 4 - Check whether list has only one Node (temp → previous and

temp → next both are NULL)

Step 5 - If it is TRUE, then assign NULL to head and delete temp. And terminate from

the function. (Setting Empty list condition)

Step 6 - If it is FALSE, then keep moving temp until it reaches to the last node in thelist. (until temp →

Lab Manual: Linear Data Structures 23


next is equal to NULL)

Step 7 - Assign NULL to temp → previous → next and delete temp.

3.3 Deleting a Specific Node from the list

We can use the following steps to delete a specific node from the double linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and

terminate the function.

Step 3 - If it is not Empty, then define a Node pointer 'temp' and initialize with head.

Step 4 - Keep moving the temp until it reaches to the exact node to be deleted or to the

last node.

Step 5 - If it is reached to the last node, then display 'Given node not found in the list!

Deletion not possible!!!' and terminate the fuction.

Step 6 - If it is reached to the exact node which we want to delete, then check whether list

is having only one node or not

Step 7 - If list has only one node and that is the node which is to be deleted then

set head to NULL and delete temp (free(temp)).

Step 8 - If list contains multiple nodes, then check whether temp is the first node in the

list (temp == head).

Step 9 - If temp is the first node, then move the head to the next node (head = head →

next), set head of previous to NULL (head → previous = NULL) and

delete temp.

Step 10 - If temp is not the first node, then check whether it is the last node in the list

Lab Manual: Linear Data Structures 24


(temp → next == NULL).

Step 11 - If temp is the last node then set temp of previous of next to NULL

(temp → previous → next = NULL) and delete temp(free(temp)).

Step 12 - If temp is not the first node and not the last node, then set temp of previous

of next to temp of next (temp → previous → next = temp→next),temp

of next of previous to temp of previous (temp → next → previous = temp →

previous) and delete temp(free(temp)).

4.Displaying

We can use the following steps to display the elements of a double linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the function.

Step 3 - If it is not Empty, then define a Node pointer 'temp' and initialize with head.

Step 4 - Display 'NULL <--- '.

Step 5 - Keep displaying temp → data with an arrow (<===>) until temp reaches to the

last node

Step 6 - Finally, display temp → data with arrow pointing to NULL

(temp → data ---> NULL)

Circular Linked List-

A circular linked list is a sequence of elements in which every element has a link to its next

element in the sequence and the last element has a link to the first element.

1.Creation

Step 1 - Define a Node structure with two members data and next

Lab Manual: Linear Data Structures 25


Step 2 - Define a Node pointer 'head' and set it to NULL.

2.Insertion

In a circular linked list, the insertion operation can be performed in three ways. They are as

follows...

2.1 Inserting At Beginning of the list

2.2 Inserting At End of the list

2.3 Inserting At Specific location in the list

2.1 Inserting At Beginning of the list

We can use the following steps to insert a new node at beginning of the circular linked list...

Step 1 - Create a newNode with given value.

Step 2 - Check whether list is Empty (head == NULL)

Step 3 - If it is Empty then, set head = newNode and newNode→next = head .

Step 4 - If it is Not Empty then, define a Node pointer 'temp' and initialize with 'head'.

Step 5 - Keep moving the 'temp' to its next node until it reaches to the last node (until

'temp → next == head').

Step 6 - Set 'newNode → next =head', 'head = newNode' and 'temp → next = head'.

2.2 Inserting At End of the list

We can use the following steps to insert a new node at end of the circular linked list...

Step 1 - Create a newNode with given value.

Step 2 - Check whether list is Empty (head == NULL).

Step 3 - If it is Empty then, set head = newNode and newNode → next = head.

Lab Manual: Linear Data Structures 26


Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.

Step 5 - Keep moving the temp to its next node until it reaches to the last node in the list

(until temp → next == head).

Step 6 - Set temp → next = newNode and newNode → next = head.

2.3 Inserting At Specific location in the list (After a Node)

We can use the following steps to insert a new node after a node in the circular linked list...

Step 1 - Create a newNode with given value.

Step 2 - Check whether list is Empty (head == NULL)

Step 3 - If it is Empty then, set head = newNode and newNode → next = head.

Step 4 - If it is Not Empty then, define a node pointer temp and initialize with head.

Step 5 - Keep moving the temp to its next node until it reaches to the node after which

we want to insert the newNode (until temp1 → data is equal to location, here

location is the node value after which we want to insert the newNode).

Step 6 - Every time check whether temp is reached to the last node or not. If it is reached

to last node then display 'Given node is not found in the list!!! Insertion not

possible!!!' and terminate the function. Otherwise move the temp to next node.

Step 7 - If temp is reached to the exact node after which we want to insert the newNode

then check whether it is last node (temp → next == head).

Step 8 - If temp is last node then set temp → next = newNode and newNode →

next = head.

Step 9 - If temp is not last node then set newNode → next = temp → next and temp →

next = newNode.

Lab Manual: Linear Data Structures 27


3. Deletion

In a circular linked list, the deletion operation can be performed in three ways those are as

follows...

3.1 Deleting from Beginning of the list

3.2 Deleting from End of the list

3.3 Deleting a Specific Node

3.1 Deleting from Beginning of the list

We can use the following steps to delete a node from beginning of the circular linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and

terminate the function.

Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and

initialize both 'temp1' and 'temp2' with head.

Step 4 - Check whether list is having only one node (temp1 → next == head)

Step 5 - If it is TRUE then set head = NULL and delete temp1 (Setting Empty list

conditions)

Step 6 - If it is FALSE move the temp1 until it reaches to the last node.

(until temp1 → next == head )

Step 7 - Then set head = temp2 → next, temp1 → next = head and delete temp2.

3.2 Deleting from End of the list

We can use the following steps to delete a node from end of the circular linked list...

Step 1 - Check whether list is Empty (head == NULL)

Lab Manual: Linear Data Structures 28


Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and

terminate the function.

Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and

initialize 'temp1' with head.

Step 4 - Check whether list has only one Node (temp1 → next == head)

Step 5 - If it is TRUE. Then, set head = NULL and delete temp1. And terminate from

the function. (Setting Empty list condition)

Step 6 - If it is FALSE. Then, set 'temp2 = temp1 ' and move temp1 to its next node.

Repeat the same until temp1 reaches to the last node in the list. (until temp1 →

next == head)

Step 7 - Set temp2 → next = head and delete temp1.

3.3 Deleting a Specific Node from the list

We can use the following steps to delete a specific node from the circular linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty then, display 'List is Empty!!! Deletion is not possible' and

terminate the function.

Step 3 - If it is Not Empty then, define two Node pointers 'temp1' and 'temp2' and

initialize 'temp1' with head.

Step 4 - Keep moving the temp1 until it reaches to the exact node to be deleted or to the

last node. And every time set 'temp2 = temp1' before moving the 'temp1' to its

next node.

Step 5 - If it is reached to the last node then display 'Given node not found in the list!

Lab Manual: Linear Data Structures 29


Deletion not possible!!!'. And terminate the function.

Step 6 - If it is reached to the exact node which we want to delete, then check whether list

is having only one node (temp1 → next== head)

Step 7 - If list has only one node and that is the node to be deleted then

set head = NULL and delete temp1 (free(temp1)).

Step 8 - If list contains multiple nodes then check whether temp1 is the first node in the

list (temp1 == head).

Step 9 - If temp1 is the first node then set temp2 = head and keep moving temp2 to its

next node until temp2 reaches to the last node. Then set head = head →

next, temp2 → next = head and delete temp1.

Step 10 - If temp1 is not first node then check whether it is last node in the list

(temp1 → next == head).

Step 1 1- If temp1 is last node then set temp2 → next = head and

delete temp1 (free(temp1)).

Step 12 - If temp1 is not first node and not last node then set

temp2 → next = temp1 → next and delete temp1 (free(temp1)).

4.Displaying a Circular Linked List

We can use the following steps to display the elements of a circular linked list...

Step 1 - Check whether list is Empty (head == NULL)

Step 2 - If it is Empty, then display 'List is Empty!!!' and terminate the function.

Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with head.

Step 4 - Keep displaying temp → data with an arrow (--->) until temp reaches to the last

Lab Manual: Linear Data Structures 30


node

Step 5 - Finally display temp → data with arrow pointing to head → data.

Program:
Write any applicable code.

Questions:

1. What are the advantages of linked lists over arrays?

2. What are the disadvantages of linked lists compared to arrays?

3. Can you explain how memory allocation works for linked lists?

4. What is the time complexity of accessing an element in a linked list?

5. What are the applications of linked lists in real-world scenarios?

6. How do you delete a node from a linked list (head, tail, or specific position)?

Experiment No: 3
Write a program for Stack and Queue Implementation:
 Stack Implementation using arrays and linked lists.

Introduction:
Stack -

Lab Manual: Linear Data Structures 31


Stack is a linear data structure in which the insertion and deletion operations are performed at only
one end. In a stack, adding and removing of elements are performed at a single position which is
known as "top".

That means, a new element is added at top of the stack and an element is removed from the top of the
stack. In stack, the insertion and deletion operations are performed based on LIFO(Last In First Out)
principle.

Stack can also be defined as

"A Collection of similar data items in which both insertion and deletion operations are
performed based on LIFO principle".

Operations on a Stack -

The following operations are performed on the stack...

1. Push (To insert an element on to the stack)

2. Pop (To delete an element from the stack)

3. Display (To display elements of the stack)

Stack data structure can be implemented in two ways. They are as follows...

1. Using Arrays

2. Using Linked List

Stack Using Arrays

A stack data structure can be implemented using a one-dimensional array. But stack implemented
using array stores only a fixed number of data values. This implementation is very simple. Just define
a one dimensional array of specific size and insert or delete the values into that array by using LIFO
principle with the help of a variable called 'top'. Initially, the top is set to -1. Whenever we want to
insert a value into the stack, increment the top value by one and then insert. Whenever we want to
delete a value from the stack, then delete the top value and decrement the top value by one.

Lab Manual: Linear Data Structures 32


I. A stack can be implemented using array as follows...

Before implementing actual operations, first follow the below steps to create an empty stack.

Step 1 - Include all the header files which are used in the program and define a constant 'SIZE' with
specific value.

Step 2 - Declare all the functions used in stack implementation.

Step 3 - Create a one dimensional array with fixed size (int stack[SIZE])

Step 4 - Define a integer variable 'top' and initialize with '-1'. (int top = -1)

Step 5 - In main method, display menu with list of operations and make suitable function calls to
perform operation selected by the user on the stack.

1. Push(value) - Inserting value into the stack

In a stack, push() is a function used to insert an element into the stack. In a stack, the new element is
always inserted at top position. Push function takes one integer value as parameter and
inserts that value into the stack.

We can use the following steps to push an element on to the stack…

Step 1 - Check whether stack is FULL. (top == SIZE-1)

Step 2 - If it is FULL, then display "Stack is FULL!!! Insertion is not possible!!!" and

terminate the function.

Step 3 - If it is NOT FULL, then increment top value by one (top++) and set stack[top] to value
(stack[top] = value).

2. Pop() - Delete a value from the Stack

3.

In a stack,pop() is a function used to delete an element from the stack. In a stack, the

Lab Manual: Linear Data Structures 33


element is always deleted from top position. Pop function does not take any value as parameter.

We can use the following steps to pop an element from the stack…

Step 1 - Check whether stack is EMPTY. (top == -1)

Step 2 - If it is EMPTY, then display "Stack is EMPTY!!! Deletion is not possible!!!" and terminate the
function.

Step 3 - If it is NOT EMPTY, then delete stack[top] and decrement top value by one (top--).

4. Display() - Displays the Elements of a Stack-

We can use the following steps to display the elements of a stack...

Step 1 - Check whether stack is EMPTY. (top == -1)

Step 2 - If it is EMPTY, then display "Stack is EMPTY!!!" and terminate the function.

Step 3 - If it is NOT EMPTY, then define a variable 'i' and initialize with top.

Display stack[i] value and decrement i value by one (i--).

Step 4 - Repeat above step until i value becomes '0'.

Source Code: To implement Stack Using Arrays

#include<iostream.h>

#include<conio.h>

#define SIZE 10

void push(int);

Lab Manual: Linear Data Structures 34


void pop();

void display();

int stack[SIZE], top = -1;

void main()

int value, choice;

clrscr();

while(1){

cout<<"\n\n***** MENU *****\n";

cout<<"1. Push\n2. Pop\n3. Display\n4. Exit";

cout<<"\nEnter your choice: ";

cin>>choice;

switch(choice)

case 1: cout<<"Enter the value to be insert: ";

cin>>value;

push(value);

break;

case 2: pop();

break;

case 3: display();

break;

case 4: exit(0);

default: cout<<"\nWrong selection!!! Try again!!!";

Lab Manual: Linear Data Structures 35


}

void push(int value)

if(top == SIZE-1)

cout<<"\nStack is Full!!! Insertion is not possible!!!";

else

top++;

stack[top] = value;

cout<<"\nInsertion success!!!";

void pop()

if(top == -1)

cout<<"\nStack is Empty!!! Deletion is not possible!!!";

else

cout<<"\nDeleted :"<<stack[top]);

top--;

Lab Manual: Linear Data Structures 36


void display()

if(top == -1)

cout<<"\nStack is Empty!!!";

else

int i;

cout<<"\nStack elements are:\n";

for(i=top; i>=0; i--)

cout<<stack[i];

II. Stack Using Linked List-

The major problem with the stack implemented using an arrays is, it works only for a fixed number of
data values. That means the amount of data must be specified at the beginning of the
implementation itself. Stack implemented using an array is not suitable, when we don't know the
size of data which we are going to use. A stack data structure can be implemented by using a linked
list data structure.

The stack implemented using linked list can work for an unlimited number of values. That means,
stack implemented using linked list works for the variable size of data. So, there is no need to fix the
size at the beginning of the implementation. The Stack implemented using linked list can organize
as many data values as we want. In linked list implementation of a stack, every new element is
inserted as 'top' element. That means every newly inserted element is pointed by 'top'. Whenever
we want to remove an element from the stack, simply remove the node which is pointed by 'top' by
moving 'top' to its previous node in the list. The next field of the first element must be always NULL

Lab Manual: Linear Data Structures 37


Stack Operations using Linked List-

We can Perform the Following Operations on Stack Using Linked List (i.e)

1. Push()

2. Pop()

3. Display()

To implement a stack using a linked list, we need to set the following things before
implementing actual operations.

Step 1 - Include all the header files which are used in the program. And declare all

the user defined functions.

Step 2 - Define a 'Node' structure with two members data and next.

Step 3 - Define a Node pointer 'top' and set it to NULL.

Step 4 - Implement the main method by displaying Menu with list of operations and make suitable
function calls in the main method.

1. Push(value) - Inserting an element into the Stack-

We can use the following steps to insert a new node into the stack...

Step 1 - Create a newNode with given value.

Step 2 - Check whether stack is Empty (top == NULL)

Step 3 - If it is Empty, then set newNode → next = NULL.

Lab Manual: Linear Data Structures 38


Step 4 - If it is Not Empty, then set newNode → next = top.

Step 5 - Finally, set top = newNode.

2. Pop() - Deleting an Element from a Stack

We can use the following steps to delete a node from the stack...

Step 1 - Check whether stack is Empty (top == NULL).

Step 2 - If it is Empty, then display "Stack is Empty!!! Deletion is not possible!!!" and terminate the
function

Step 3 - If it is Not Empty, then define a Node pointer 'temp' and set it to 'top'.

Step 4 - Then set 'top = top → next'.

Step 5 - Finally, delete 'temp'. (free(temp)).

3. Display() - Displaying stack of elements

We can use the following steps to display the elements (nodes) of a stack...

Step 1 - Check whether stack is Empty (top == NULL).

Step 2 - If it is Empty, then display 'Stack is Empty!!!' and terminate the function.

Step 3 - If it is Not Empty, then define a Node pointer 'temp' and initialize with top.Step 4 - Display
'temp → data --->' and move it to the next node. Repeat the same until temp reaches to the first node
in the stack. (temp → next != NULL).

Step 5 - Finally! Display 'temp → data ---> NULL'.

Questions:

1. What is the difference between a circular queue and a linear queue?

2. What is queue overflow and underflow?

3. How do priority queues differ from regular queues?

Lab Manual: Linear Data Structures 39


4. How is a queue used in CPU scheduling?

Experiment No: 4
Write a program for Stack and Queue Implementation:
 Queue Implementation using arrays and linked lists.

Lab Manual: Linear Data Structures 40


I . Queue
A queue data structure can be implemented using one dimensional array. The queue implemented
using array stores only fixed number of data values. The implementation of queue data structure using
array is very simple. Just define a one dimensional array of specific size and insert or delete the values
into that array by using FIFO (First In First Out) principle with the help of variables 'front' and 'rear'.
Initially both 'front' and 'rear' are set to -1. Whenever, we want to insert a new value into the queue,
increment 'rear' value by one and then insert at that position. Whenever we want to delete a value from
the queue, then delete the element which is at 'front' position and increment 'front' value by one.

Queue Operations using Array-


We can Perform the following operations on Queue

1.enQueue()

2.deQueue()

3.Display()

Before we implement actual operations, first follow the below steps to create an empty queue.

Step 1 - Include all the header files which are used in the program and define a

constant 'SIZE' with specific value.

Step 2 - Declare all the user defined functions which are used in queue

implementation.

Step 3 - Create a one dimensional array with above defined SIZE (int

queue[SIZE]).

Step 4 - Define two integer variables 'front' and 'rear' and initialize both with '-1'.

(int front = -1, rear = -1).

Step 5 - Then implement main method by displaying menu of operations list and make suitable
function calls to perform operation selected by the user on queue.

1. enQueue(value) - Inserting value into the queue-

In a queue data structure, enQueue() is a function used to insert a new element into the queue. In a
queue, the new element is always inserted at rear position. The enQueue() function takes one integer
value as a parameter and inserts that value into the queue. We can use the following steps to insert an

Lab Manual: Linear Data Structures 41


element into the queue…

Step 1 - Check whether queue is FULL. (rear == SIZE-1)

Step 2 - If it is FULL, then display "Queue is FULL!!! Insertion is not

possible!!!" and terminate the function.

Step 3 - If it is NOT FULL, then increment rear value by one (rear++) and

set queue[rear] = value.

2. deQueue() - Deleting a value from the Queue-

In a queue data structure, deQueue() is a function used to delete an element from the queue. In a queue,
the element is always deleted from front position. The deQueue() function does not take any value as
parameter. We can use the following steps to delete an element from the queue…

Step 1 - Check whether queue is EMPTY. (front == rear)

Step 2 - If it is EMPTY, then display "Queue is EMPTY!!! Deletion is not

possible!!!" and terminate the function.

Step 3 - If it is NOT EMPTY, then increment the front value by one (front ++). Then

display queue[front] as deleted element. Then check whether

both front and rear are equal (front == rear), if it TRUE, then set

both front and rear to '-1' (front = rear = -1).

3. Display() - Displays the elements of a Queue

We can use the following steps to display the elements of a queue…

Step 1 - Check whether queue is EMPTY. (front == rear)

Step 2 - If it is EMPTY, then display "Queue is EMPTY!!!" and terminate the function.

Step 3 - If it is NOT EMPTY, then define an integer variable 'i' and set 'i = front+1'.

Step 4 - Display 'queue[i]' value and increment 'i' value by one (i++). Repeat the same until 'i' value
reaches to rear (i <= rear).

II. Queue Using Linked List -


The major problem with the queue implemented using an array is, It will work for an only fixed

Lab Manual: Linear Data Structures 42


number of data values. That means, the amount of data must be specified at the beginning itself. Queue
using an array is not suitable when we don't know the size of data which we are going to use. A queue
data structure can be implemented using a linked list data structure. The queue which is implemented
using a linked list can work for an unlimited number of values. That means, queue using linked list can
work for the variable size of data (No need to fix the size at the beginning of the implementation). The
Queue implemented using linked list can organize as many data values as we want. In linked list
implementation of a queue, the last inserted node is always pointed by 'rear' and the first node is
always pointed by 'front'.

To implement queue using linked list, we need to set the following things before implementing

actual operations.

Step 1 - Include all the header files which are used in the program. And declare all the user defined
functions.

Step 2 - Define a 'Node' structure with two members data and next.

Step 3 - Define two Node pointers 'front' and 'rear' and set both to NULL.

Step 4 - Implement the main method by displaying Menu of list of operations and make suitable
function calls in the main method to perform user selected operation.

1.enQueue(value) - Inserting an element into the Queue

We can use the following steps to insert a new node into the queue…

Step 1 - Create a newNode with given value and set 'newNode → next' to NULL.

Step 2 - Check whether queue is Empty (rear == NULL)

Step 3 - If it is Empty then, set front = newNode and rear = newNode.

Step 4 - If it is Not Empty then, set rear → next = newNode and rear = newNode.

2. deQueue() - Deleting an Element from Queue

We can use the following steps to delete a node from the queue…

tep 1 - Check whether queue is Empty (front == NULL).

Step 2 - If it is Empty, then display "Queue is Empty!!! Deletion is not possible!!!" and terminate from
the function

Step 3 - If it is Not Empty then, define a Node pointer 'temp' and set it to 'front'.

Step 4 - Then set 'front = front → next' and delete 'temp' (free(temp)).

3. Display() - Displaying the elements of Queue

We can use the following steps to display the elements (nodes) of a queue...

Lab Manual: Linear Data Structures 43


Step 1 - Check whether queue is Empty (front == NULL).

Step 2 - If it is Empty then, display 'Queue is Empty!!!' and terminate the function.

Step 3 - If it is Not Empty then, define a Node pointer 'temp' and initialize with front.

Step 4 - Display 'temp → data --->' and move it to the next node. Repeat the same until

'temp' reaches to 'rear' (temp → next != NULL).

Step 5 - Finally! Display 'temp → data ---> NULL'.

Program To implement Queue using Linked List

#include<iostream.h>

#include<conio.h>

struct Node

int data;

struct Node *next;

}*front = NULL,*rear = NULL;

void insert(int);

void delete();

void display();

void main()

int choice, value;

clrscr();

cout<<"\n:: Queue Implementation using Linked List ::\n";

while(1){

cout<<"\n****** MENU ******\n";

cout<<"1. Insert\n2. Delete\n3. Display\n4. Exit\n";

cout<<"Enter your choice: ";

Lab Manual: Linear Data Structures 44


cin>>choice);

switch(choice){

case 1: cout<<"Enter the value to be insert: ";

cin>>value;

insert(value);

break;

case 2: delete(); break;

case 3: display(); break;

case 4: exit(0);

default: cout<<"\nWrong selection!!! Please try again!!!\n";

void insert(int value)

struct Node *newNode;

newNode = (struct Node*)malloc(sizeof(struct Node));

newNode->data = value;

newNode -> next = NULL;

if(front == NULL)

front = rear = newNode;

else{

rear -> next = newNode;

rear = newNode;

cout<<"\nInsertion is Success!!!\n";

Lab Manual: Linear Data Structures 45


}

void delete()

if(front == NULL)

cout<<"\nQueue is Empty!!!\n";

else{

struct Node *temp = front;

front = front -> next;

cout<<"\nDeleted element: %d\n", temp->data;

free(temp);

void display()

if(front == NULL)

cout<<"\nQueue is Empty!!!\n";

else{

struct Node *temp = front;

while(temp->next != NULL){

cout<<temp->data;

temp = temp -> next;

cout<<temp->data;

Lab Manual: Linear Data Structures 46


Questions:

5. What is the difference between a circular queue and a linear queue?

6. What is queue overflow and underflow?

7. How do priority queues differ from regular queues?

8. How is a queue used in CPU scheduling?

Lab Manual: Linear Data Structures 47


Experiment No: 5

Write a program for Implementation of Array Operations:

 Searching (Linear Search).

 Searching ( Binary Search).

Introduction:
Searching is the fundamental process of locating a specific element or item within a collection of data.
This collection of data can take various forms, such as arrays, lists, trees, or other structured
representations.The primary objective of searching is to determine whether the desired element exists
within the data, and if so, to identify its precise location or retrieve it. It plays an important role in
various computational tasks and real-world applications, including information retrieval, data analysis,
decision-making processes, and more.

Importance of Searching in DSA

 Efficiency: Efficient searching algorithms improve program performance.


 Data Retrieval: Quickly find and retrieve specific data from large datasets.
 Database Systems: Enables fast querying of databases.
 Problem Solving: Used in a wide range of problem-solving tasks.

commonly used searching algorithms:

Linear Search: In this simple algorithm, each element in the collection is sequentially checked until the
desired item is found, or the entire list is traversed. It is suitable for small-sized or unsorted lists, but its
time complexity is O(n) in the worst case.

Binary Search: This algorithm is applicable only to sorted lists. It repeatedly compares the middle
element of the list with the target element and narrows down the search range by half based on the
comparison result. Binary search has a time complexity of O(log n), making it highly efficient for large
sorted lists.

Lab Manual: Linear Data Structures 48


i)LINEAR SEARCH (SEQUENTIAL SEARCH):
Search begins by comparing the first element of the list with the target element. If it matches, the
search ends. Otherwise, move to next element and compare. In this way, the target element is
compared with all the elements until a match occurs. If the match do not occur and there are no more
elements to be compared, conclude that target element is absent in the list.

Algorithm for Linear search :


Linear_Search (A[ ], N, val , pos )
Step 1 : Set pos = -1 and k = 0
Step 2 : Repeat while k < N Begin
Step 3 : if A[ k ] = val
Set pos = k
print pos
Goto step 5
End while
Step 4 : print “Value is not present”
Step 5 : Exit

Program:

/*searching an element using linear search technique*/


#include<stdio.h>
#include<conio.h>
void main(){
int list[20],size,i,sElement;
printf("Enter size of the list: ");
scanf("%d",&size);
printf("Enter any %d integer values: ",size);
for(i = 0; i < size; i++)
scanf("%d",&list[i]);
printf("Enter the element to be Search: ");
scanf("%d",&sElement);

// Linear Search Logic


for(i = 0; i < size; i++)
{
if(sElement == list[i])
{

Lab Manual: Linear Data Structures 49


printf("Element is found at %d index", i);
break;
}
}
if(i == size)
printf("Given element is not found in the list!!!");
getch();
}

(ii)Binary Search:
Before searching, the list of items should be sorted in ascending order. First compare the key value
with the item in the mid position of the array. If there is a match, we can return immediately the
position. if the value is less than the element in middle location of the array, the required value is lie in
the lower half of the array. If the value is greater than the element in middle location of the array, the
required value is lie in the upper half of the array. We repeat the above procedure on the lower half or
upper half of the array.

Algorithm:

Binary_Search (A [ ], U_bound, VAL)


Step 1 : set BEG = 0 , END = U_bound , POS = -1
Step 2 : Repeat while (BEG <= END )
Step 3 :set MID = ( BEG + END ) / 2
Step 4 :if A [ MID ] == VAL then
POS = MID
print VAL “ is available at “, POS
GoTo Step 6
End if
if A [ MID ] > VAL then
set END = MID – 1
Else
set BEG = MID + 1
End if
End while
Step 5 : if POS = -1 then
print VAL “ is not present “
End if
Step 6 : EXIT

Lab Manual: Linear Data Structures 50


Program:
/* implementation of the binary search*/
#include<stdio.h>
#include<conio.h>
void main()
{
int first, last, middle, size, i, sElement, list[100];
clrscr();
printf("Enter the size of the list: ");
scanf("%d",&size);
printf("Enter %d integer values in Assending order\n", size);
for (i = 0; i < size; i++)
scanf("%d",&list[i]);
printf("Enter value to be search: ");
scanf("%d", &sElement);
first = 0;
last = size - 1;
middle = (first+last)/2;
while (first <= last) {
if (list[middle] < sElement)
first = middle + 1;
else if (list[middle] == sElement) {
printf("Element found at index %d.\n",middle);
break;
}
else
last = middle - 1;
middle = (first + last)/2;
}
if (first > last)
printf("Element Not found in the list.");
getch();
}

Questions:

1. Search the element given array(24,13,56,35,46,27,78,48) using binary search.


2. Define searching. Explain different types of searching.

Lab Manual: Linear Data Structures 51


3. complexity of Linear search and Binary search.

Experiment No:6
Write a program for Implementation of following Sorting Algorithms:
 Bubble Sort
 Merge Sort
 Quick Sort

Introduction:
Sorting refers to rearrangement of a given array or list of elements according to a comparison operator
on the elements. The comparison operator is used to decide the new order of elements in the
respective data structure.

Why Sorting Algorithms are Important-


The sorting algorithm is important in Computer Science because it reduces the complexity of a
problem. There is a wide range of applications for these algorithms, including searching algorithms,
database algorithms, divide and conquer methods, and data structure algorithms.
 When you have hundreds of datasets you want to print, you might want to arrange them in some
way.
 Once we get the data sorted, we can get the k-th smallest and k-th largest item in O(1) time.
 Searching any element in a huge data set becomes easy. We can use Binary search method for
search if we have sorted data. So, Sorting become important here.
 They can be used in software and in conceptual problems to solve more advanced problems.

Different Sorting Algorithms-


 Bubble Sort
 Selection Sort
 Insertion Sort
 Merge Sort
 Quicksort
 Counting Sort
 Radix Sort
 Bucket Sort
 Heap Sort
 Shell Sort
Lab Manual: Linear Data Structures 52
i) Bubble sort -

The bubble sort is an example of exchange sort.In this method,repetitive comparisonis performed
among elements and essential swapping of elements is done. Bubble sort is commonly used in sorting
algorithms. It is easy to understand but time consuming i.e. takes more number of comparisons to
sort a list. In this type, two successive elements are comparedand swapping is done.Thus,step-by-step
entire array elements are checked. It is different from the selection sort. Instead of searching the
minimum element and then applying swapping, two records are swapped instantly upon noticing that
they are not in order.

Algorithm:

Bubble_Sort ( A [ ] , N )
Step 1: Start
Step 2: Take an array of n elements
Step 3: for i=0,………….n-2
Step 4: for j=i+1,…….n-1
Step 5: if arr[j]>arr[j+1] then
Interchange arr[j] and arr[j+1]
End of if
Step 6: Print the sorted array arr
Step 7:Stop

Program:

#include <stdio.h>

// perform the bubble sort


void bubbleSort(int array[], int size) {

// loop to access each array element


for (int step = 0; step < size - 1; ++step) {

// loop to compare array elements


for (int i = 0; i < size - step - 1; ++i) {

// compare two adjacent elements


// change > to < to sort in descending order
if (array[i] > array[i + 1]) {

// swapping occurs if elements


// are not in the intended order
int temp = array[i];
Lab Manual: Linear Data Structures 53
array[i] = array[i + 1];
array[i + 1] = temp;
}
}
}
}

// print array
void printArray(int array[], int size) {
for (int i = 0; i < size; ++i) {
printf("%d ", array[i]);
}
printf("\n");
}

int main() {
int data[] = {-2, 45, 0, 11, -9};

// find the array's length


int size = sizeof(data) / sizeof(data[0]);

bubbleSort(data, size);

printf("Sorted Array in Ascending Order:\n");


printArray(data, size);
}

ii) Merge sort:

Merge Sort is like a wise sage who knows that the best way to tackle a problem is by breaking it down.
It is a recursive method, which means it calls itself to solve smaller parts of a larger problem. Imagine
splitting a deck of cards into halves, over and over, until you have piles so small they're already sorted.
Here's a simple way to visualize Merge Sort:

 Divide: Split your array of data in half, again and again, until each piece can't be divided further
(you'll end up with arrays of just one element).
 Conquer: Now, with each piece being sorted (since it's just one element), you start combining them.
 Merge: As you combine these pieces, you sort them along the way. Think of merging two small
stacks of cards where each stack is already in order.

This process continues until all the small, sorted pieces are merged back into a single, sorted array.

Algorithm

Step 1: Create two pointers, one for each sorted half.

Lab Manual: Linear Data Structures 54


Step 2: Initialize an empty temporary array to hold the merged result.
Step 3: Compare the elements at the pointers of the two halves:
Copy the smaller element into the temporary array.
Move the pointer of the sublist with the smaller element forward.
Step 4: Repeat step 3 until one of the sublists is empty.
Step 5: Copy the remaining elements from the non-empty sublist to the temporary array.
Step 6: Copy the elements back from the temporary array to the original list.

Program:

#include <stdio.h>
#define max 10
int a[11] = { 10, 14, 19, 26, 27, 31, 33, 35, 42, 44, 0 };
int b[10];
void merging(int low, int mid, int high){
int l1, l2, i;
for(l1 = low, l2 = mid + 1, i = low; l1 <= mid && l2 <= high; i++) {
if(a[l1] <= a[l2])
b[i] = a[l1++];
else
b[i] = a[l2++];
}
while(l1 <= mid)
b[i++] = a[l1++];
while(l2 <= high)
b[i++] = a[l2++];
for(i = low; i <= high; i++)
a[i] = b[i];
}
void sort(int low, int high){
int mid;
if(low < high) {
mid = (low + high) / 2;
sort(low, mid);
sort(mid+1, high);
merging(low, mid, high);
} else {
return;
}
}
int main(){
int i;
printf("Array before sorting");
for(i = 0; i <= max; i++)
Lab Manual: Linear Data Structures 55
printf("%d ", a[i]);
sort(0, max);
printf("Array after sorting");
for(i = 0; i <= max; i++)
printf("%d ", a[i]);
}

iii) Quick sort:

It is a divide and conquer algorithm. Quick sort first divides a large array into two smaller sub-arrays:
the low elements and the high elements. Quick sort can then recursively sort the sub-arrays.

ALGORITHM:

Step 1: Pick an element, called a pivot, from the array.


Step 2: Partitioning: reorder the array so that all elements with values less than the pivot come
before the pivot, while all elements with values greater than the pivot come after it (equal values
can go either way). After this partitioning, the pivot is in its final position. This is called the
partition operation.
Step 3: Recursively apply the above steps to the sub-array of elements with smaller values
and separately to the sub-array of elements with greater values.
Program:

#include <stdio.h>
#include <stdbool.h>
#define MAX 7
int intArray[MAX] = { 4,6,3,2,1,9,7};

void printline(int count) {


int i;
for (i = 0; i < count - 1; i++) {
printf("=");
}
printf("=");
}
void display() {
int i;
printf("[");

// navigate through all items


for (i = 0; i < MAX; i++) {
printf("%d ", intArray[i]);
}
printf("]");
Lab Manual: Linear Data Structures 56
}
void swap(int num1, int num2) {
int temp = intArray[num1];
intArray[num1] = intArray[num2];
intArray[num2] = temp;
}
int partition(int left, int right, int pivot) {
int leftPointer = left - 1;
int rightPointer = right;
while (true) {
while (intArray[++leftPointer] < pivot) {
//do nothing
}
while (rightPointer > 0 && intArray[--rightPointer] > pivot) {
//do nothing
}

if (leftPointer >= rightPointer) {


break;
} else {
printf(" item swapped :%d,%d", intArray[leftPointer], intArray[rightPointer]);
swap(leftPointer, rightPointer);
}
}

printf(" pivot swapped :%d,%d", intArray[leftPointer], intArray[right]);


swap(leftPointer, right);
printf("Updated Array: ");
display();
return leftPointer;
}

void quickSort(int left, int right) {


if (right - left <= 0) {
return;
} else {
int pivot = intArray[right];
int partitionPoint = partition(left, right, pivot);
quickSort(left, partitionPoint - 1);
quickSort(partitionPoint + 1, right);
}
}

int main() {
printf("Input Array: ");
display();
Lab Manual: Linear Data Structures 57
printline(50);
quickSort(0, MAX - 1);
printf("Output Array: ");
display();
printline(50);
}

Questions:

1. What is the time complexity of Merge Sort?


2. What are the key steps in the Merge Sort algorithm?
3. How does Merge Sort differ from Quick Sort?

Experiment No:7
Write a program for Implementation direct access file:

Introduction -
A Direct Access File allows random access to records using a hash function. Unlike sequential files,
where records are accessed one by one, direct access files enable efficient record management by
mapping keys to specific file locations.
Hash Function:
A mathematical function that computes the address of a record in the file based on its key.
Address=key%Total Records

Record Size:
Each record occupies a fixed amount of space in the file to ensure consistency during access.

Lab Manual: Linear Data Structures 58


File Operations:

Write: Stores a record at a location derived from the hash function.


Read: Fetches a record directly using its key.
Update: Modifies a record in place.
Delete: Marks a record as deleted (by clearing its space)

Algorithm
1. Write Record
Input: Key, Data
Output: Record written to the file

I. Compute the address using the hash function:


Address=key%Total Records
II. Seek to the calculated location in the file.
III.Write the data padded to the record size.
2. Read Record
Input: Key
Output: Data at the specified key or "Not Found"

I. Compute the address using the hash function.


II. Seek to the location and read the record.
III. Return the record if found; otherwise, indicate it is missing.

3. Update Record
Input: Key, New Data
Output: Confirmation of update

I. Compute the address using the hash function.


II. Check if data exists at the address.
III.If found, overwrite the record with the new data.
4. Delete Record
Input: Key
Output: Confirmation of deletion

I. Compute the address using the hash function.


II. Overwrite the record space with null bytes.

Lab Manual: Linear Data Structures 59


Program:

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

#define FILE_NAME "direct_access_file.bin"


#define RECORD_SIZE 20 // Fixed size for each record
#define TOTAL_RECORDS 100 // Total number of records

// Function to calculate the hash address


int hash_function(int key) {
return key % TOTAL_RECORDS;
}

// Initialize the file with empty data


void initialize_file() {
FILE *file = fopen(FILE_NAME, "wb");
if (!file) {
printf("Error creating file.\n");
return;
}
char empty_record[RECORD_SIZE] = {0};
for (int i = 0; i < TOTAL_RECORDS; i++) {
fwrite(empty_record, RECORD_SIZE, 1, file);
}
fclose(file);
}

// Write a record into the file


void write_record(int key, char *data) {
int location = hash_function(key) * RECORD_SIZE;
FILE *file = fopen(FILE_NAME, "r+b");
if (!file) {
printf("Error opening file.\n");
return;
}
fseek(file, location, SEEK_SET);
char record[RECORD_SIZE] = {0};
strncpy(record, data, RECORD_SIZE - 1); // Ensure data fits the record size
fwrite(record, RECORD_SIZE, 1, file);
fclose(file);
printf("Record with key %d written successfully.\n", key);
}

Lab Manual: Linear Data Structures 60


// Read a record from the file
void read_record(int key) {
int location = hash_function(key) * RECORD_SIZE;
FILE *file = fopen(FILE_NAME, "rb");
if (!file) {
printf("Error opening file.\n");
return;
}
fseek(file, location, SEEK_SET);
char record[RECORD_SIZE] = {0};
fread(record, RECORD_SIZE, 1, file);
fclose(file);

if (strlen(record) > 0) {
printf("Record found: %s\n", record);
} else {
printf("Record not found.\n");
}
}

// Update an existing record in the file


void update_record(int key, char *new_data) {
int location = hash_function(key) * RECORD_SIZE;
FILE *file = fopen(FILE_NAME, "r+b");
if (!file) {
printf("Error opening file.\n");
return;
}
fseek(file, location, SEEK_SET);
char record[RECORD_SIZE] = {0};
fread(record, RECORD_SIZE, 1, file);

if (strlen(record) > 0) {
fseek(file, location, SEEK_SET);
strncpy(record, new_data, RECORD_SIZE - 1);
fwrite(record, RECORD_SIZE, 1, file);
printf("Record with key %d updated successfully.\n", key);
} else {
printf("Record not found for update.\n");
}
fclose(file);
}

// Delete a record from the file


void delete_record(int key) {
Lab Manual: Linear Data Structures 61
int location = hash_function(key) * RECORD_SIZE;
FILE *file = fopen(FILE_NAME, "r+b");
if (!file) {
printf("Error opening file.\n");
return;
}
fseek(file, location, SEEK_SET);
char empty_record[RECORD_SIZE] = {0};
fwrite(empty_record, RECORD_SIZE, 1, file);
fclose(file);
printf("Record with key %d deleted successfully.\n", key);
}

// Main program with menu-driven interface


int main() {
int choice, key;
char data[RECORD_SIZE];

// Initialize file on the first run


FILE *file_check = fopen(FILE_NAME, "rb");
if (!file_check) {
initialize_file();
} else {
fclose(file_check);
}

while (1) {
printf("\nDirect Access File Operations:\n");
printf("1. Write Record\n");
printf("2. Read Record\n");
printf("3. Update Record\n");
printf("4. Delete Record\n");
printf("5. Exit\n");
printf("Enter your choice: ");
scanf("%d", &choice);

switch (choice) {
case 1:
printf("Enter key (integer): ");
scanf("%d", &key);
printf("Enter data: ");
scanf("%s", data);
write_record(key, data);
break;
case 2:
printf("Enter key (integer): ");
Lab Manual: Linear Data Structures 62
scanf("%d", &key);
read_record(key);
break;
case 3:
printf("Enter key (integer): ");
scanf("%d", &key);
printf("Enter new data: ");
scanf("%s", data);
update_record(key, data);
break;
case 4:
printf("Enter key (integer): ");
scanf("%d", &key);
delete_record(key);
break;
case 5:
printf("Exiting program.\n");
exit(0);
default:
printf("Invalid choice. Try again.\n");
}
}

return 0;
}

Questions:

1. · What is a direct access file?


2. · How is direct access different from sequential access?
3. · What is the purpose of a hash function in direct access files?
4. · What are the advantages of using direct access files?
5. · What are the disadvantages or limitations of direct access files?

Lab Manual: Linear Data Structures 63

You might also like