SHIVAM
SHIVAM
SHIVAM
Data Structures
(3130702)
Enrolment No 230160107100
Branch COMPUTER
CERTIFICATE
This is to certify that Mr./Ms. PRAJAPATI SHIVAM RAJARAM
Enrollment No. 230160107103 of B.E. Semester 3 oomutter eeuartment
Engineering of this Instittte (GTU oode: 3330704 ) has satisfactorily comuleted
the Practical.
/ Tttorial work for the stbject DATA STRUCTURE (3130702) for the academic
year 2024 -25
Place:
Date:
Preface
Main motto of any laboratory/practical/field work is for enhancing required skills as well as
creating ability amongst students to solve real time problem by developing relevant competencies
in psychomotor domain. By keeping in view, GTU has designed competency focused outcome-
based curriculum for engineering degree programs where sufficient weightage is given to
practical work. It shows importance of enhancement of skills amongst the students and it pays
attention to utilize every second of time allotted for practical amongst students, instructors and
faculty members to achieve relevant outcomes by performing the experiments rather than having
merely study type experiments. It is must for effective implementation of competency focused
outcomebased curriculum that every practical is keenly designed to serve as a tool to develop and
enhance relevant competency required by the various industry among every student. These
psychomotor skills are very difficult to develop through traditional chalk and board content
delivery method in the classroom. Accordingly, this lab manual is designed to focus on the
industry defined relevant outcomes, rather than old practice of conducting practical to prove
concept and theory.
By using this lab manual students can go through the relevant theory and procedure in advance
before the actual performance which creates an interest and students can have basic idea prior to
performance. This in turn enhances pre-determined outcomes amongst students. Each experiment
in this manual begins with competency, industry relevant skills, course outcomes as well as
practical outcomes (objectives). The students will also achieve safety and necessary precautions
to be taken while performing practical.
This manual also provides guidelines to faculty members to facilitate student centric lab activities
through each experiment by arranging and managing necessary resources in order that the
students follow the procedures with required safety and necessary precautions to achieve the
outcomes. It also gives an idea that how students will be assessed by providing rubrics.
Data Structures is a core course in all computer science undergraduate curricula. The course is
the basis for understanding several data structures and also algorithms that operate on them. The
course forms the foundation for almost all computer science subjects: compilers, operating
systems, databases, AI and software engineering. The course comes with a lab in most universities
in India. The associated lab in university curricula focuses on implementation of algorithms
operating on the data structures, i.e., coding programs on the data structures and algorithms.
Data Structure (3130702) 230160107100
DTE’s Vision
Institute’s Vision
To be a leading institution ensuring Academic Excellence, Research, Nurturing Innovation and Attitude
to produce competent technocrats for service to Nation.
Department’s Vision
Department’s Mission
To create globally competent students having the ability to design, develop and test world class
software, keeping pace with the latest technological developments.
Create facilities and expertise in advanced computer technology thereby promote research.
Enhance Industry Institute Interaction program to get acquainted with corporate culture.
Induce moral, ethical values and spirit of social commitment.
Sr. CO CO CO CO CO
No. Practical Outcome/Title of experiment
1 2 3 4 5
2. Queue
Data Structure (3130702) 230160107100
2.1 Write a program to implement QUEUE using arrays
that performs following operations (a) INSERT (b)
DELETE (c) DISPLAY
2.2 Write a program to implement Circular Queue using
arrays that performs following operations. (a) √ √
INSERT (b) DELETE (c) DISPLAY
2.3 Identify widely used application which use Queue
data structure for implementation of its important
feature.
6. Tree
7. Graph
8. Searching
9. Sorting
Data Structure (3130702) 230160107100
9.1 Write a program to implement Quick Sort √
9.2 Write a program to implement Merge Sort
9.3 Write a program to implement Bubble Sort
9.4 Identify widely used application which use Sorting
technique for implementation of its important
feature.
The following industry relevant competencies are expected to be developed in the student by
undertaking the practical work of this laboratory.
1. Will be able to classify data structures and identify storage representation of primitive and
nonprimitive data structures
2. Will be able to implement various operations on Stack, Queue, Link list, Tree, Graph, Hashing
and File operations.
3. Will be able to understand need of sorting and searching for various applications
4. Will be able to apply various data structure to design real time applications in efficient manner.
1. Teacher should provide the guideline with demonstration of practical to the students with all
features.
2. Teacher shall explain basic concepts/theory related to the experiment to the students before
starting of each practical
3. Involve all the students in performance of each experiment.
Data Structure (3130702) 230160107100
4. Teacher is expected to share the skills and competencies to be developed in the students and
ensure that the respective skills and competencies are developed in the students after the
completion of the experimentation.
5. Teachers should give opportunity to students for hands-on experience after the demonstration.
6. Teacher may provide additional knowledge and skills to the students even though not covered
in the manual but are expected from the students by concerned industry.
7. Give practical assignment and assess the performance of students based on task assigned to
check whether it is as per the instructions or not.
8. Teacher is expected to refer complete curriculum of the course and follow the guidelines for
implementation.
1. Students are expected to carefully listen to all the theory classes delivered by the faculty
members and understand the COs, content of the course, teaching and examination scheme, skill
set to be developed etc.
2. Students will have to perform experiments on computer system on which C/C++ compiler is
installed to execute programs of data structure.
3. Students should develop programs and execute all the programs using C/C++ compiler. Students
have to show output of each program in their practical file.
4. Students are instructed to submit practical list as per given sample list shown on next page.
5. Student should develop a habit of submitting the experimentation work as per the schedule and
s/he should be well prepared for the same.
Index
(Progressive Assessment Sheet)
Date
of Date of Assessme Sign. of
Sr. Objective(s) of Experiment Page Remar
No. No. perfor submiss nt Teacher
mance ion Marks with date ks
Data Structure (3130702) 230160107100
2. Queue
6.
Tree
6.1 Write a program which create binary
search tree.
6.2 Implement recursive tree traversing
methods in-order, pre-order and post-order
traversal.
6.3 Identify widely used application which use
Tree data structure for implementation of
its important feature.
Data Structure (3130702) 230160107100
7. Graph
8. Searching
8.1 Write a program to implement Linear
Search.
8.2 Write a program to implement Binary
Search.
8.3 Identify widely used application which
use Searching technique
for implementation of its important feature.
9. Sorting
9.1 Write a program to implement Quick Sort
9.2 Write a program to implement Merge Sort
9.3 Write a program to implement Bubble Sort
9.4 Identify widely used application which
use Sorting technique for implementation of
its important feature.
Total
Data Structure (3130702) 230160107100
Experiment No – 1
AIM : Classification of Data Structure and Stack
1.3 Implement a program to convert infix notation to postfix notation using stack.
1.4 Write a program to implement Tower of Hanoi problem.
1.5 Identify widely used application which use stack data structure for implementation of its important
feature.
Date:
Theory:
Data Structure
Data structures are a fundamental concept in computer science that enable efficient storage and
manipulation of data. They are used to organize and store data in a manner that allows for optimal
performance of algorithms. The selection of a suitable data structure begins with the choice of an
abstract data type, which defines the operations that can be performed on the data. Well-designed
data structures can perform a wide range of critical operations while using minimal resources such
14
Data Structure (3130702) 230160107100
as execution time and memory space. In essence, data structure introduction refers to the
arrangement of data in a computer's memory in a way that enables rapid access by the processor for
the required calculations.
Stack
A stack is a data structure that follows the last-in first-out (LIFO) principle, meaning that objects
are inserted and removed from the container in a particular order. In pushdown stacks, only two
operations are allowed: pushing an item onto the stack, and popping an item off the top of the stack.
Access to the stack is limited, as elements can only be added and removed from the top. When an
item is pushed onto the stack, it becomes the new top item. Conversely, when an item is popped off
the stack, it is removed from the top.
To illustrate this concept, consider a stack of books. Just as you can only remove the top book, you
can only add a new book to the top of the stack. A stack can also have a limited capacity. If the
stack is already full and there is no space to add a new item, it is said to be in an overflow state. On
the other hand, if the stack is empty and an item is removed, it is in an underflow state, meaning
that no items are present in the stack to be removed.
A stack is an abstract data structure that operates on the LIFO principle, where the last item added
is the first item to be removed. Items can be inserted and deleted at one end called the top, creating
a structure that resembles a closed tube on one side.
The add operation of the stack is called push operation The delete operation is called as
pop operation.
Push operation on a full stack causes stack overflow.
Pop operation on an empty stack causes stack underflow. SP is a
pointer, which is used to access the top element of the stack.
If you push elements that are added at the top of the stack; In the same way when we pop the
elements, the element at the top of the stack is deleted.
(1) PUSH
(2) POP
In-fix- to Postfix Conversion:
Procedure to convert from infix expression to postfix expression is as follows:
15
Data Structure (3130702) 230160107100
4. If the symbol scanned is a right parenthesis, continue to pop all items from the stack and place
them into the postfix expression output until a matching left parenthesis is found.
5. If the scanned symbol is an operator, remove all operators from the stack and place them in the
postfix expression output if and only if the precedence of the operator on top of the stack is
greater than or equal to the precedence of the scanned operator. Then push the scanned operator
onto the stack; otherwise, push the scanned operator onto the stack.
of Data Structures:
1. Primitive data structures: Primitive data structures are simple data structures
constructed using the standard data types of a computer language. Examples of primitive
data structures include variables, arrays, pointers, structures, unions, and more. These
structures are used to build more complex data structures
Linear data structures are arranged as a continuous set of data elements in the memory
and can be constructed using array data types. In linear data structures, the adjacency
relationship between data elements is maintained.
Add an element
Delete an element
Traverse
Sort the list of elements Search for a data element
16
Data Structure (3130702) 230160107100
Stack
Queue Tables
List Linked
Lists.
(b) Non-linear Data Structure:
Non-linear data structures are not arranged in a continuous manner and include data
structures such as trees and graphs. These structures can be used to represent complex
relationships between data elements.
Add elements
Delete elements
Display the elements
Sort the list of elements Search for a data element
Tree
Decision tree
Graph Forest
1.2 Implement a program for stack that performs following operations using array. (a)
PUSH (b) POP (c) PEEP (d) CHANGE (e) DISPLAY
Program:
#include<stdio.h>
#define size 5
struct stack
{ int a[size],top; int temp[size];
}s;
// CHANGE Operation
void main()
{
s.top = -1; int choice, index,
new_element; do
{
printf("\n STACK IMPLEMENTATION PROGRAM"); printf("\n 1. PUSH
2. POP 3. PEEP 4. CHANGE 5. DISPLAY 0. EXIT\n"); printf("\n
Enter your choice: "); scanf("%d", &choice);
switch(choice) {
case 1:
if(s.top == size-1)
{
printf("\tSTACK OVERFLOW\n");
} else
18
Data Structure (3130702) 230160107100
{
push();
}
break;
case 2: if(s.top == -1)
{
printf("\tSTACK UNDERFLOW\n");
} else
pop();
}
break;
case 3: if(s.top == -1)
{ printf("\tStack is empty.\n");
} else
peep();
}
break;
case 4:
printf(" Enter index no : ");
scanf("%d",&index); if(index<0 || index>s.top)
{
printf("\tINVALID INDEX NUMBER\n");
} else
display();
}
break;
case 0:
printf("\tEND OF
PROGRAM"); break; default :
printf("\tINVALID CHOICE\n");
}
1.3 Implement a program to convert infix notation to postfix notation using stack.
Program:
20
Data Structure (3130702) 230160107100
char st[MAX];
int top=-1;
void push(char st[], char); char pop(char st[]);
void InfixtoPostfix(char source[], char target[]); int
getPriority(char);
int main()
21
Data Structure (3130702) 230160107100
EXPRESSION");exit(1);
}
} while((top!=-1) &&
(st[top]!='('))
{ target[j] = pop(st); j++;
}
target[j]='\0';
Output:
22
Data Structure (3130702) 230160107100
Program:
#include <stdio.h> void
main()
Output:
1.5 Identify widely used application which use stack data structure for implementation of its
important feature.
Stack Applications:
23
Data Structure (3130702) 230160107100
1. Stack is used by compilers to check for balancing of parentheses, brackets and braces.
2. Stack is used to evaluate a postfix expression.
3. Stack is used to convert an infix expression into postfix/prefix form. 4. In recursion, all
intermediate arguments and return values are stored on the processor’s stack.
5. During a function call the return address and arguments are pushed onto a stack and on return
they are popped off. 6. Depth first search uses a stack data structure to find an element from a
graph.
Conclusion:
Data structures are vital for efficient data organization and manipulation, enhancing algorithm
performance while minimizing resource usage. Choosing the right structure, whether linear (like
stacks and queues) or non-linear (like trees and graphs), is key to optimizing computational tasks.
Quiz:
Criteria FIFO (First In, First Out) LIFO (Last In, First Out)
Order The first element added is the first The last element added is the first
one removed (e.g., Queue). one removed (e.g., Stack).
Data Structure Queue (uses FIFO principle) Stack (uses LIFO principle)
24
Data Structure (3130702) 230160107100
Use Cases Used in scheduling tasks, buffering, Used in undo mechanisms,
managing tasks in order. function call management,
recursive algorithms.
Real-world Waiting in a line (first person in Stack of plates (you take the plate
Analogy line is served first). from the top).
•
Example: A B + • Also does not need parentheses or
precedence rules.
Suggested Reference:
25
Data Structure (3130702) 230160107100
Problem Coding Completeness
Logic
Understanding Standards and accuracy Q&A
Building (2)
Rubrics (2) (2) (2) Total
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)
Marks
Experiment No: 2
AIM : Queue
2.1 Write a program to implement QUEUE using arrays that performs following
operations (a)INSERT (b) DELETE (c) DISPLAY
2.2 Write a program to implement Circular Queue using arrays that performs following
operations. (a) INSERT (b) DELETE (c) DISPLAY
2.3 Identify widely used application which uses Queue data structure for implementation
of its important feature.
Date:
Theory:
Queue
26
Data Structure (3130702) 230160107100
A queue is a data structure that follows the First In, First Out (FIFO) principle. It is a special type
of list where items are inserted at the rear and deleted from the front end. Queues can be compared
to real-world scenarios, such as people waiting in line at a bank.
Queue Circular
Queue
D-Queue
Priority Queue
2.1 Write a program to implement QUEUE using arrays that performs following
operations. (a)INSERT (b) DELETE (c) DISPLAY
Program:
#include <stdio.h>
#define MAX 5
int queue[MAX];
int front = -1, rear = -1;
27
Data Structure (3130702) 230160107100
// Function to display the elements of the
queue void display() { if (front == -1) {
printf("Queue is empty\n");
} else { printf("Queue elements are:
");
for (int i = front; i <= rear; i++) { printf("%d
", queue[i]); }
printf("\n");
} }
switch (choice) {
case 1:
printf("Enter the value to insert:
"); scanf("%d", &value); insert(value);
break; case 2: delete(); break; case 3:
display(); break; case 4: return 0; default:
printf("Invalid choice\n");
}
}
28
Data Structure (3130702) 230160107100
}
Output:
2.2 Write a program to implement Circular Queue using arrays that performs following
operations. (a) INSERT (b) DELETE (c) DISPLAY
Program:
#include <stdio.h>
#define MAX 5
int queue[MAX];
int front = -1, rear = -1;
// Function to insert an element into the circular queue void insert(int value) {
if ((front == 0 && rear == MAX - 1) || (rear == (front - 1) % (MAX - 1))) {
printf("Queue Overflow\n");
} else { if (front == -1) { // First element insertion
front = rear = 0;
} else if (rear == MAX - 1 && front != 0) { rear =
0; // Wrap around to the beginning
} else
29
Data Structure (3130702) 230160107100
{ rear++; } queue[rear] = value; printf("%d
inserted into the queue\n", value); } }
}
} else { for (int i = front; i <
MAX; i++) { printf("%d ",
queue[i]);
}
for (int i = 0; i <= rear; i++) {
printf("%d ", queue[i]);
} }
printf("\n");
}
switch (choice) {
case 1:
printf("Enter the value to insert:
"); scanf("%d", &value); insert(value);
30
Data Structure (3130702) 230160107100
break; case 2: delete(); break; case 3:
display(); break; case 4: return 0; default:
printf("Invalid choice\n");
}
}
}
Output:
31
Data Structure (3130702) 230160107100
2.3 Identify widely used application which uses Queue data structure for implementation
of its important feature.
One of the most widely used applications of the queue data structure is in printer spooling. In printer
spooling, documents that are to be printed are placed in a queue, and the printer processes them in a
32
Data Structure (3130702) 230160107100
FirstIn-First-Out (FIFO) order. Each job waits its turn, ensuring that the first job sent to the printer is
printed first, followed by subsequent jobs in the order they were received.
Conclusion:
A circular queue improves upon the limitations of a linear queue by efficiently utilizing memory through
its wrap-around mechanism, allowing the rear to loop back to the start when space is available. This
structure maintains the First-In-First-Out (FIFO) principle and is commonly used in applications like CPU
scheduling and network buffering. Unlike a linear queue, which can waste space after elements are
deleted, a circular queue ensures continuous, efficient use of available memory. Quiz:
A circular queue is a queue in which the last A priority queue is a queue where each element is
position is connected to the first, forming a circle. associated with a priority. Elements are removed
This allows the queue to reuse empty spaces created based on their priority, not necessarily in the order
by the removal of elements, making better use of they were inserted (higher-priority elements are
memory. dequeued first).
Operates on the FIFO principle but with circular Operates based on priority rather than FIFO, where
memory management. the highest-priority elements are processed first.
33
Data Structure (3130702) 230160107100
Used in scenarios like circular buffers and resource Used in scheduling systems, like CPU job
scheduling. scheduling, where tasks with higher priority are
executed first.
Insertion and deletion follow the FIFO order with Insertion order can differ from removal order based
wrap-around. on priority levels.
Suggested Reference:
1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G. Sorenson
Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
Marks
Experiment No: 3
3.1 Write a menu driven program to implement following operations on the singly linked
list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Insert a node such that linked list is in ascending order. (According to INFO field)
(d) Delete a first node of the linked list.
(e) Delete a node before specified position. (f)
Delete a node after specified position.
34
Data Structure (3130702) 230160107100
3.2 Write a program to implement stack using linked list 3.3 Write
a program to implement queue using linked list.
Date:
A linked list is a type of data structure that stores a collection of non-sequential data items. Unlike
arrays, linked lists are dynamic and their size can be changed during program execution. Each data
item in a linked list has a pointer that holds the memory address of the next data item in the list. The
data items in a linked list may not be stored in consecutive memory locations, but their pointers
make it easy to access them in any order.
A singly linked list, also known as a linear linked list, is a type of linked list in which all nodes are
connected together sequentially. Each node in a singly linked list contains data and a pointer to the
next node. The last node's pointer is set to null. The limitation of a singly linked list is that it can
only be traversed in one direction, in a forward direction.
Insert
- Insert at first position
- Insert at last position
- Insert into ordered list Delete
Traverse list (Print list) Copy linked list
35
Data Structure (3130702) 230160107100
3.1 Write a menu driven program to implement following operations on the singly linked
list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Insert a node such that linked list is in ascending order.(According to INFO field)
(d) Delete a first node of the linked list.
(e) Delete a node before specified position. (f)
Delete a node after specified position.
Program:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data; struct Node*
next;
};
if (head == NULL) {
head = newNode;
} else { struct Node* temp = head;
while (temp->next != NULL) { temp
= temp->next;
}
temp->next = newNode;
} printf("%d inserted at the end.\n", value);
}
36
Data Structure (3130702) 230160107100
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = value; newNode->next = NULL;
37
Data Structure (3130702) 230160107100
} else { printf("Invalid
position.\n");
}
}
int main() { int choice, value, pos; while (1) { printf("\nMenu:\n"); printf("1. Insert at Front\n2. Insert
at End\n3. Insert in Ascending Order\n4. Delete First Node\n5. Delete Before Position\n6.
Delete After Position\n7. Display List\n8. Exit\n"); printf("Enter your choice: "); scanf("%d",
&choice);
switch (choice) {
case 1:
printf("Enter value to insert at front: ");
38
Data Structure (3130702) 230160107100
scanf("%d", &value);
insertAtFront(value);
break;
case 2:
printf("Enter value to insert at end: ");
scanf("%d", &value); insertAtEnd(value);
break; case
3:
printf("Enter value to insert in ascending order:
"); scanf("%d", &value);
insertInOrder(value); break;
case 4:
deleteFirstNode();
break;
case 5:
printf("Enter position before which to delete:
"); scanf("%d", &pos); deleteBeforePosition(pos);
break;
case 6:
printf("Enter position after which to delete:
"); scanf("%d", &pos); deleteAfterPosition(pos);
break;
case 7: displayList();
break; case 8:
exit(0);
default: printf("Invalid choice.\n");
} }
return 0;
} O u
t
p
39
Data Structure (3130702) 230160107100
u
t:
40
Data Structure (3130702) 230160107100
Program:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct
Node* next; };
41
Data Structure (3130702) 230160107100
= top; top = top->next; printf("%d popped from
stack.\n", temp->data); free(temp);
} }
int main() {
int choice, value;
while (1) {
printf("\nStack Operations:\n"); printf("1. Push\n2.
Pop\n3. Display Stack\n4. Exit\n");
printf("Enter your choice: "); scanf("%d",
&choice);
switch (choice) {
case 1:
printf("Enter value to push:
"); scanf("%d", &value);
push(value); break; case 2:
pop(); break; case 3:
displayStack();
break; case 4: exit(0); default:
printf("Invalid choice.\n");
} } return 0;
}
Output:
42
Data Structure (3130702) 230160107100
Program:
#include <stdio.h>
#include <stdlib.h>
struct Node {
43
Data Structure (3130702) 230160107100
int data; struct
Node* next;
};
if (rear == NULL) {
front = rear = newNode;
} else { rear->next = newNode;
rear = newNode;
}
printf("%d enqueued to queue.\n", value); }
if (front == NULL) {
rear = NULL;
}
printf("%d dequeued from queue.\n", temp->data);
free(temp);
}
}
while (1) {
printf("\nQueue Operations:\n");
printf("1. Enqueue\n2. Dequeue\n3. Display Queue\n4. Exit\n");
printf("Enter your choice: "); scanf("%d", &choice);
switch (choice) {
case 1:
printf("Enter value to enqueue: ");
Output:
45
Data Structure (3130702) 230160107100
Conclusion:
1. Traversal: Visit all the nodes in the linked list starting from the head.
2. Insertion: Insert a new node at the beginning, end, or at a specified position in the list.
o Insertion at the beginning (head). o Insertion at the end (tail).
o Insertion after a specified node. 3. Deletion: Remove a node from the
list. o Deletion at the beginning (head). o Deletion at the end (tail).
o Deletion of a specified node.
4. Search: Search for an element by value in the list.
5. Update: Modify the data of a node in the list.
6. Reversal: Reverse the order of the nodes in the list.
Unidirectional Traversal: Singly linked lists can only be traversed in one direction (from head to
tail), making reverse traversal difficult.
Extra Memory Usage: Each node requires additional memory for storing the pointer to the next
node, which can be more memory-intensive than arrays.
No Random Access: You can't directly access elements by index like in an array. You need to
traverse the list from the head to find an element.
Inefficient Search: Searching for an element requires traversing the list, which takes O(n) time.
Suggested Reference:
Marks
Experiment No: 4
4.1 Write a program to implement following operations on the doubly linked list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Delete a last node of the linked list. (d) Delete a node before specified position.
Date:
47
Data Structure (3130702) 230160107100
Theory:
A doubly linked list is a data structure where each node contains data and two pointers - one to point
to the previous node (LPTR) and another to point to the next node (RPTR). The main advantage of
a doubly linked list is that we can traverse it in any direction, either forward or backward. Another
advantage is that we can delete a node with ease since we have pointers to both the previous and
next nodes. In contrast, a node on a singly linked list cannot be removed unless we have a pointer
to its predecessor. However, the drawback of a doubly linked list is that it requires more memory
than a singly linked list since we need an extra pointer to point to the previous node. In the image,
L and R denote the leftmost and rightmost nodes in the list, respectively. The left link of the L node
and the right link of the R node are both NULL, indicating the end of the list for each direction.
Insert
- Insert at first position
- Insert at last position
- Insert into ordered list Delete
Traverse list (Print list) Copy linked list
4.1 Write a program to implement following operations on the doubly linked list.
(a) Insert a node at the front of the linked list.
(b) Insert a node at the end of the linked list.
(c) Delete a last node of the linked list. (d) Delete a node before specified position.
48
Data Structure (3130702) 230160107100
(a) Insert a node at the front of the linked list.
Program:
#include <stdio.h>
#include <stdlib.h>
Program:
#include <stdio.h>
#include <stdlib.h>
insert_at_end(&head, 10);
insert_at_end(&head, 20); insert_at_end(&head,
30); display(head);
return 0;
}
Output:
#include <stdio.h>
#include <stdlib.h>
51
Data Structure (3130702) 230160107100
// If there is only one node in the list if ((*head)->next ==
NULL) { printf("Deleted node with data %d\n", (*head)>data);
free(*head); *head = NULL; return;
}
// Function to insert a node at the end (for testing purposes) void insert_at_end(struct
Node** head, int data) { struct Node* new_node = (struct
Node*)malloc(sizeof(struct
Node)); struct Node* last = *head; new_node->data = data; new_node->next = NULL;
if (*head == NULL) {
new_node->prev = NULL;
*head = new_node;
return;
}
52
Data Structure (3130702) 230160107100
// Main function to test deletion of the last node int main()
{
struct Node* head = NULL;
insert_at_end(&head, 10);
insert_at_end(&head, 20); insert_at_end(&head,
30);
display(head);
delete_last_node
(&head);
display(head);
return 0;
}
Output:
Program:
#include <stdio.h>
#include <stdlib.h>
53
Data Structure (3130702) 230160107100
}
temp = temp->next;
}
// Function to insert a node at the end (for testing purposes) void insert_at_end(struct
Node** head, int data) { struct Node* new_node = (struct
Node*)malloc(sizeof(struct
Node)); struct Node* last = *head; new_node->data = data; new_node->next = NULL;
if (*head == NULL) {
new_node->prev = NULL;
*head =
new_node; return;
}
54
Data Structure (3130702) 230160107100
// Main function to test deletion before a specified position int
main() { struct Node* head = NULL;
insert_at_end(&head, 10);
insert_at_end(&head, 20);
insert_at_end(&head, 30);
insert_at_end(&head, 40);
insert_at_end(&head, 50);
display(head);
return 0;
}
Output:
Conclusion:
In this implementation of the doubly linked list in C, we demonstrated several fundamental operations,
including inserting nodes at both the front and end of the list, deleting the last node, and deleting a node
before a specified position.
Quiz:
(1) Explain structure of a node of doubly link list A node in a doubly linked list consists of
three components:
55
Data Structure (3130702) 230160107100
3. Previous Pointer (prev): Points to the previous node in the sequence. It is used for
backward traversal.
Suggested Reference:
1. An Introduction to Data Structures with Applications. by Jean-Paul Tremblay & Paul G. Sorenson
Publisher-Tata McGraw Hill.
2. Data Structures using C & C++ -By Ten Baum Publisher – Prenctice-Hall International
3. Fundamentals of Computer Algorithms by Horowitz, Sahni,Galgotia Pub. 2001 ed.
4. http://www.geeksforgeeks.org/data-structures/
5. http://www.coursera.org/specializations/data-structures-algorithms
56
Data Structure (3130702) 230160107100
Rubric-wise marks obtained:
Marks
Experiment No: 5
5.1 Write a program to implement following operations on the circular linked list.
(a) Insert a node at the end of the linked list.
(b) Insert a node before specified position.
(c) Delete a first node of the linked list.
(d) Delete a node after specified position.
5.2 Identify widely used application which uses linked list for implementation of its
important feature.
Date:
Theory:
57
Data Structure (3130702) 230160107100
Circular linked list
A circular linked list is similar to a singly linked list, except that the last node points to the first
node, creating a circular arrangement of nodes. Unlike a singly linked list, it does not contain null
pointers. Traversal can only be done in one direction, i.e., the forward direction. The biggest
advantage of a circular linked list is that it saves time when we want to go from the last node to the
first node because it directly points to the first node. A good example of an application where a
circular linked list can be used is a time-sharing problem that can be solved by the operating system.
Insert
- Insert at first position
- Insert at last position
- Insert into ordered list Delete
Traverse list (Print list)
5.1 Write a program to implement following operations on the circular linked list.
(a) Insert a node at the end of the linked list.
(b) Insert a node before specified position.
(c) Delete a first node of the linked list. (d) Delete a node after specified position.
(a) Insert a node at the end of the linked list.
Program:
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data; struct Node*
next;
};
if (last == NULL) {
last = new_node; last->next = last; // Pointing to
itself
} else { new_node->next = last-
>next; last->next =
new_node; last = new_node;
58
Data Structure (3130702) 230160107100
}
}
return 0; } Output:
Program:
#include <stdio.h>
#include <stdlib.h>
struct Node* last = NULL; void insert_end(int data) { struct Node* new_node = (struct
Node*)malloc(sizeof(struct Node)); new_node- >data =
data;
if (last == NULL) {
last = new_node; last->next
= last;
} else {
new_node->next = last->next; last-
>next = new_node; last
59
Data Structure (3130702) 230160107100
= new_node;
}
}
int main() {
insert_end(10);
insert_end(20);
insert_end(30);
display();
insert_before_position(15, 2);
display();
60
Data Structure (3130702) 230160107100
return 0;
}
Output:
Program:
#include <stdio.h>
#include <stdlib.h>
struct Node* last = NULL; void insert_end(int data) { struct Node* new_node = (struct
Node*)malloc(sizeof(struct Node)); new_node- >data =
data;
if (last == NULL) {
last = new_node; last->next
= last;
} else {
new_node->next = last->next; last-
>next = new_node; last
= new_node;
}
}
61
Data Structure (3130702) 230160107100
}
int main() {
insert_end(10);
insert_end(20);
insert_end(30);
display();
delete_first(); display();
return 0; } Output:
Program:
#include <stdio.h>
#include <stdlib.h>
struct Node* last = NULL; void insert_end(int data) { struct Node* new_node = (struct
Node*)malloc(sizeof(struct Node)); new_node- >data =
data;
62
Data Structure (3130702) 230160107100
if (last == NULL) {
last = new_node; last->next
= last;
} else { new_node->next =
last- >next; last->next =
new_node; last = new_node;
}
}
free(node_to_delete);
}
int main() {
insert_end(10);
insert_end(20);
63
Data Structure (3130702) 230160107100
insert_end(30); display();
Output:
5.2 Identify widely used application which uses linked list for implementation of its
important feature.
One widely used application of linked lists is the implementation of dynamic memory allocation
systems like the malloc() function in C. In systems that manage free and used memory blocks, a
linked list is used to track allocated and free memory segments, facilitating dynamic memory
allocation.
Conclusion:
In this exercise, we implemented various operations on a circular linked list in C, including inserting
a node at the end, inserting a node before a specified position, deleting the first node, and deleting a
node after a specified position. Each of these operations demonstrated how circular linked lists
maintain connectivity through circular pointers, making them efficient for situations where we need
continuous looping of data. Quiz:
1. Complexity in Implementation: Circular linked lists are more complex to implement than linear
linked lists due to the need to manage the circular connections properly. This complexity can lead
to bugs and make maintenance more challenging.
2. Increased Memory Overhead: Each node in a circular linked list requires extra memory for the
pointer, which can be significant in cases where many small data elements are stored.
3. Traversal Issues: Traversing a circular linked list requires careful handling to avoid infinite loops.
Special conditions must be implemented to break out of the loop when needed, particularly when
performing operations like searching or deleting nodes.
4. Difficulty in Finding the Last Node: Unlike singly or doubly linked lists, where the last node can
be easily identified, in a circular linked list, there is no straightforward way to access the last node
without traversing the entire list.
64
Data Structure (3130702) 230160107100
5. Limited Use Cases: While circular linked lists have their advantages, they are not as widely
applicable as other data structures (like arrays or regular linked lists), limiting their use in certain
situations.
Marks
66
Data Structure (3130702) 230160107100
Experiment No: 6
AIM : Tree
Date:
Theory:
A binary search tree is a binary tree in which each node possessed a key that satisfy the following
conditions
1. All key (if any) in the left sub tree of the root precedes the key in the root.
2. The key in the root precedes all key (if any) in the right sub tree. 3. The left and right sub tree sub
trees of the root are again search trees.
Operations on tree
The most common operations performed on tree structure are that of traversal. This is a procedure by
which each node in the tree is processed exactly once in a systematic manner.
67
Data Structure (3130702) 230160107100
2. In-order Traversal
3. Post-order Traversal Pre-order
In-order
Post-order
Program:
#include <stdio.h>
#include <stdlib.h>
68
Data Structure (3130702) 230160107100
// Function to create a new node struct Node* createNode(int data) { struct Node* newNode =
(struct Node*)malloc(sizeof(struct Node)); newNode-
>data = data; newNode->left = newNode-
>right = NULL; return newNode;
}
return root;
}
// Main function
int main() { struct Node* root
= NULL;
return 0; } Output:
69
Data Structure (3130702) 230160107100
6.2 Implement recursive tree traversing methods in-order, preorder and post-order
traversal.
Program:
70
Data Structure (3130702) 230160107100
// Traversals printf("In-
order traversal: ");
inorder(root);
printf("\n");
return 0; } Output:
6.3 Identify widely used applications which use Tree data structure for implementation of
its important feature.
• Hierarchical Data Representation: Trees represent hierarchical data structures, such as file
systems and organizational charts, allowing for efficient organization and retrieval.
• Database Indexing: Trees, especially B-trees and binary search trees, are commonly used in
databases to index data, enabling fast search, insertion, and deletion operations.
• Network Routing Algorithms: Trees are used in network routing protocols (e.g., spanning
trees) to minimize costs and optimize data transmission paths in network topologies.
• Expression Parsing and Evaluation: Abstract syntax trees (ASTs) are utilized in compilers
and interpreters to represent and evaluate expressions, making it easier to analyze and
transform code.
• Artificial Intelligence: Decision trees are widely used in machine learning for classification
and regression tasks, helping to make decisions based on input features.
Conclusion:
In this program, we successfully implemented the Binary Search Tree (BST) along with its insertion
operation and recursive tree traversal methods (in-order, pre-order, and post-order). The in-order
traversal provided sorted output of the BST, while pre-order and post-order gave different sequences
useful for various applications. Binary Search Trees are efficient for searching, insertion, and deletion
71
Data Structure (3130702) 230160107100
operations due to their structured arrangement, which makes them an essential data structure in both
theory and practical applications. The traversal techniques allow for systematic exploration of the tree
based on the specific order of node visitation. Quiz:
A Binary Search Tree (BST) is a data structure that consists of nodes, where each node has
a maximum of two children: a left child and a right child. The left subtree of a node contains
only nodes with keys less than the node's key, and the right subtree contains only nodes with
keys greater than the node's key. This property allows for efficient searching, insertion, and
deletion operations, typically with a time complexity of O(log n) in a balanced tree.
(2) Explain pre-order, in-order and post order traversal techniques Pre- order
Traversal:
• In pre-order traversal, the nodes are visited in the following order: Root, Left, Right. This means
the root node is visited first, then the left subtree, followed by the right subtree. It is commonly
used for creating a copy of the tree or in prefix expressions.
• Example: Pre-order of the tree 50, 30, 70, 20, 40, 60, 80 is 50 30 20 40 70 60 80.
In-order Traversal:
• In in-order traversal, the nodes are visited in the following order: Left, Root, Right. This traversal
results in visiting the nodes in ascending order when applied to a Binary Search Tree. It is
commonly used for retrieving data in sorted order.
• Example: In-order of the tree 50, 30, 70, 20, 40, 60, 80 is 20 30 40 50 60 70 80.
Post-order Traversal:
• In post-order traversal, the nodes are visited in the following order: Left, Right, Root. This means
the root node is visited last, after the left and right subtrees. It is often used in applications where
nodes need to be deleted or for postfix expressions.
• Example: Post-order of the tree 50, 30, 70, 20, 40, 60, 80 is 20 40 30 60 80 70 50.
72
Data Structure (3130702) 230160107100
• In text input systems such as search engines or mobile keyboard auto-completion, binary search
trees can be used to suggest words by storing dictionary words in the tree structure. Routing
Algorithms:
• Network routing algorithms use BSTs (or their variants) to determine the most efficient route for
data to travel from one node to another.
Suggested Reference:
Marks
73
Data Structure (3130702) 230160107100
Experiment No: 7
AIM : Graph
Date:
Theory:
Graph:
A graph G can be defined as a non-empty set of vertices or nodes (V) and a set of edges (E) that
represents the relationship or connection between those nodes. The edges can be defined as a
mapping from E to pairs of elements of V. A graph can be represented as G = (V, E), where V
represents the set of nodes and E represents the set of edges. Each edge of the graph G can be
associated with a pair of nodes of the graph. If an edge X belongs to E and is associated with a pair
of nodes (u, v), where u and v belong to V, then we say that edge X connects node u and node v.
DFS is a graph traversal algorithm that is similar to the preorder traversal of a tree. The traversal
can start from any vertex vi of the graph. Initially, the vertex vi is visited, and then all the adjacent
vertices to vi are traversed recursively using DFS. As a graph can have cycles, we need to avoid
74
Data Structure (3130702) 230160107100
revisiting a node. To achieve this, when a vertex V is visited, it is marked as visited and should not
be selected for traversal again.
• Breadth First Search (BFS) starts from a vertex v0 and marks it as visited. Then, all the vertices
adjacent to v0 are visited next.
• Let the vertices adjacent to v0 be v1, v2, v3, and v4. These vertices are marked as visited.
• All unvisited vertices adjacent to v1, v2, v3, and v4 are visited next.
• The above process continues until all vertices are visited.
• The algorithm for BFS maintains a list of vertices that have been visited but not explored for
adjacent vertices. This list is stored in a queue. • The queue initially contains the starting vertex.
• In each iteration, a vertex is removed from the queue, and its adjacent vertices, which have not
been visited yet, are added to the queue. • The algorithm terminates when the queue becomes
empty.
Program:
#include <stdio.h>
#include <stdlib.h>
75
Data Structure (3130702) 230160107100
// Function to create a graph
struct Graph* createGraph(int vertices) { struct Graph* graph = malloc(sizeof(struct
Graph)); graph- >numVertices = vertices;
visited[startVertex] = 1; enqueue(queue,
startVertex);
77
Data Structure (3130702) 230160107100
struct Node* temp = graph- >adjLists[vertex]; while
(temp) { int
adjVertex = temp->vertex; if
(!visited[adjVertex]) { dfs(graph,
adjVertex, visited);
}
temp = temp->next;
} }
addEdge(graph, 0, 1);
addEdge(graph, 0, 4);
addEdge(graph, 1, 2);
addEdge(graph, 1, 3);
addEdge(graph, 1, 4);
addEdge(graph, 2, 3);
addEdge(graph, 3, 4);
return 0;
}
Output:
7.2 Identify widely used applications which use graphs data structure for implementation
of its important feature. Social Networks:
Graphs are used to model social relationships. Nodes represent users, and edges represent
connections or friendships.
Routing Algorithms:
Graphs are fundamental in network routing protocols to find the shortest path for data
transmission across a network (e.g., Dijkstra's algorithm).
Recommendation Systems:
Graphs are utilized to find relationships between users and items in recommendation
systems, enhancing user experience by suggesting relevant content.
Game Development:
Graphs are used for pathfinding algorithms (like A* or Dijkstra) in games to navigate
characters or vehicles through environments.
Dependency Resolution:
In build systems, tasks and their dependencies can be represented as graphs to determine
the order of execution.
Network Topologies:
Graphs are used to model various network topologies (e.g., star, mesh) in
telecommunications and computer networks.
Transportation Systems:
Graphs represent transportation networks, with nodes as locations and edges as paths,
allowing for route optimization.
Circuit Design:
Graphs model electrical circuits, where components are represented as nodes and
connections as edges, aiding in analysis and design.
Biological Networks:
Graphs are used to model biological systems, such as protein-protein interaction networks
or gene regulatory networks, for studying biological functions.
Conclusion:
In this section, we implemented both Breadth-First Search (BFS) and Depth-First Search (DFS)
algorithms for graph traversal using a graph represented by an adjacency list in C. BFS explores
nodes layer by layer, making it ideal for finding the shortest path in unweighted graphs, while DFS
explores as far as possible down one branch before backtracking, which is useful for scenarios such
as topological sorting or pathfinding in mazes. Quiz:
79
Data Structure (3130702) 230160107100
Traversal Method Explores as far as possible down Uses a queue to keep track of the
one branch before backtracking. next node to visit.
Data Structure Used Uses a stack (or recursion) to Uses a queue to keep track of the
keep track of the next node to next node to visit.
visit.
Space Complexity O(h), where h is the height of the O(b^d), where b is the branching
tree; can be O(n) in the worst factor and d is the depth of the
case for highly unbalanced trees. shallowest solution; can be more
memory-intensive.
Traversal Order Visits nodes in depth order, Visits nodes in breadth order,
exploring child nodes before exploring all nodes at the current
sibling nodes. depth before moving to the next
level.
1. Social Networks:
o Modeling relationships between individuals, where nodes represent users and edges
represent friendships or connections.
2. Web Page Link Structures:
o Representing the internet as a graph, where web pages are nodes and hyperlinks are directed
edges. This structure is used in search engines for indexing and ranking.
3. Routing Algorithms: o Used in network routing protocols to find the shortest path for
data transmission between nodes (e.g., Dijkstra's algorithm, A* algorithm).
80
Data Structure (3130702) 230160107100
4. Transportation Systems:
o Modeling road networks where intersections are nodes and roads are edges. This is used for
route planning and optimization.
5. Recommendation Systems:
o Graphs can represent relationships between users and items, facilitating personalized content
suggestions in e-commerce or streaming services.
6. Dependency Resolution:
o Managing dependencies between tasks in project management tools, where nodes represent
tasks and edges represent dependencies.
7. Game Development:
o Pathfinding algorithms for character movement in games, using graphs to navigate complex
terrains.
8. Circuit Design:
o Modeling electrical circuits as graphs, where components are nodes and connections are
edges, aiding in analysis and design. o
9. Biological Networks: o Representing interactions in biological systems, such as protein-
protein interaction networks or gene regulatory networks.
10. Data Organization:
• Representing hierarchical data structures, such as file systems or organizational charts, using directed
graphs.
Suggested Reference:
81
Data Structure (3130702) 230160107100
Marks
Experiment No: 8
AIM : Searching
Date:
Theory:
Linear/Sequential Search
• Linear search, also known as sequential search, is a technique used in computer science to find
a specific value in a list by sequentially checking each of its elements one at a time until the
desired one is found.
• It is the simplest search algorithm and a form of brute-force search. Its worst-case cost is
proportional to the number of elements in the list.
Binary Search
82
Data Structure (3130702) 230160107100
• If we have an array that is sorted, we can use a much more efficient algorithm called Binary
Search.
• In Binary Search, we divide the array into two equal halves and compare the middle element
with the search element.
• If the middle element is equal to the search element, we have found the element and return its
index; otherwise, if the middle element is less than the search element, we look at the right part
of the array, and if the middle element is greater than the search element, we
look at the left part of the array.
Program:
#include <stdio.h>
return 0;
} Output:
83
Data Structure (3130702) 230160107100
Program:
#include <stdio.h>
// Main function
int main() { int arr[] = {1, 2, 3, 4, 5, 8};
// Sorted
array int size = sizeof(arr) / sizeof(arr[0]); int
target = 5; int result = binarySearch(arr, size,
target);
return 0; } Output:
84
Data Structure (3130702) 230160107100
8.3 Identify widely used applications which use Searching technique for implementation
of its important feature.
1. Database Querying:
Searching algorithms are used to efficiently retrieve records from databases based on specific
criteria.
2. Search Engines:
• Search engines utilize various searching techniques to retrieve relevant documents from a vast amount
of data based on user queries.
3. Text Editors:
• Functionality like "Find" in text editors implements searching algorithms to locate specific text within
documents.
4. File Systems:
• Searching techniques are employed in file systems to locate files and directories quickly based on
names or metadata.
5. Sorting and Searching Algorithms:
• Many algorithms, such as quicksort and mergesort, use searching techniques to efficiently organize
data.
6. E-commerce:
• Online shopping platforms use searching algorithms to help users find products quickly by name,
category, or other attributes.
7. Artificial Intelligence:
• In AI, searching techniques are employed in pathfinding algorithms (like A*) and game AI to find
optimal solutions.
8. Network Routing:
• Searching algorithms are used in routing protocols to find optimal paths for data packets across
networks.
9. Data Analysis:
• Searching techniques help in locating and extracting specific data points from large datasets for
analysis and visualization.
10. Machine Learning:
• In machine learning, searching algorithms can be used for feature selection, model optimization,
and hyperparameter tuning.
Conclusion:
In this section, we implemented two fundamental searching algorithms: Linear Search and Binary Search.
Linear Search traverses each element in a list until it finds the target, making it simple but inefficient for
large datasets, with a time complexity of O(n). On the other hand, Binary Search is significantly faster for
sorted arrays, reducing the search space by half with each iteration, achieving a time complexity of O(log
n)
Quiz:
85
Data Structure (3130702) 230160107100
(1) List out searching algorithms
• Linear Search: A simple search algorithm that checks each element in a list until the desired
element is found.
• Binary Search: An efficient algorithm that finds an item in a sorted array by repeatedly dividing
the search interval in half.
• Jump Search: A searching algorithm for sorted arrays that works by jumping ahead by fixed
steps and performing linear search in between.
• Exponential Search: An algorithm that finds the range where an element may exist and then
applies binary search within that range.
• Interpolation Search: A search algorithm that estimates the position of the target value within
a sorted array based on the values at the ends of the search range.
• Fibonacci Search: A searching technique that uses Fibonacci numbers to divide the array into
smaller parts.
• Ternary Search: A search algorithm that divides the array into three parts and eliminates one
of the three parts based on the comparison with the target value.
• Sublist Search: An algorithm to find a sublist within a list (or a substring within a string).
Data Requirement Can be used on unsorted and Requires a sorted array to function
sorted lists. correctly.
Time Complexity O(n) (worst case, where n is the O(log n) (worst case, where n is
number of elements). the number of elements).
Best Use Case Best for small or unsorted lists Best for large, sorted lists where
where sorting is not feasible. search efficiency is crucial.
86
Data Structure (3130702) 230160107100
• Version Control Systems: Finding specific versions or changes in a sorted history of commits. •
Autocomplete Features: Suggesting words from a sorted dictionary based on user input.
Suggested Reference:
Marks
Experiment No: 9
AIM : Sorting
Date:
87
Data Structure (3130702) 230160107100
Relevant CO: CO4, CO5
Theory:
Bubble sort
Bubble sort, also known as sinking sort, is a comparison-based sorting algorithm. It works by
repeatedly scanning through the list to be sorted, comparing adjacent elements and swapping them
if they are not in the correct order. In each pass through the list, the largest element bubbles up to
the top. The algorithm repeats these processes until no more swaps are needed, indicating that the
list is sorted. Although it is simple to understand and implement, bubble sort has a worst-case and
average time complexity of O(n^2), making it too slow for large inputs. Insertion sort is a more
efficient alternative for small lists.
Merge Sort
• The merge sort algorithm is based on the classical divide-and-conquer paradigm. It operates as
follows:
DIVIDE: Partition the n-element sequence to be sorted into two sub sequences of n/2
elements each.
CONQUER: Sort the two sub sequences recursively using the merge sort.
COMBINE: Merge the two sorted sub sequences of size n/2 each to produce the sorted
sequence consisting of n elements.
Quick Sort
Quicksort is currently the fastest known sorting algorithm and often the most practical choice for
sorting, with an average expected running time of O(n log(n)). Its operation consists of the following
steps: • Pick an element from the array, known as a pivot.
88
Data Structure (3130702) 230160107100
• Reorder the array so that all elements with values less than the pivot are placed before it, while
all elements with values greater than the pivot come after it (elements with equal values can go
either way). This operation is called partitioning, and at the end of it, the pivot is in its final
position.
• Recursively apply the above steps to the sub-arrays of elements with smaller and greater values,
respectively. Quicksort, like merge sort, is a divide-and-conquer recursive algorithm.
• The basic divide-and-conquer process for sorting a sub array is given in the following three easy
steps:
Divide
Conquer Combine
Program:
#include <stdio.h>
89
Data Structure (3130702) 230160107100
Sort): \n");
return 0; } Output:
Program:
#include <stdio.h>
90
Data Structure (3130702) 230160107100
} else { arr[k] = R[j]; j++;
} k++;
}
// Main function
int main() {
int arr[] = {12, 11, 13, 5, 6, 7}; int
n = sizeof(arr) / sizeof(arr[0]);
mergeSort(arr, 0, n - 1); printf("Sorted array
(Merge
Sort): \n");
for (int i = 0; i < n; i++) { printf("%d
", arr[i]);
} printf("\n");
return 0;
}
Output:
91
Data Structure (3130702) 230160107100
9.3 Write a program to implement Bubble Sort
Program:
#include <stdio.h>
return 0; } Output:
9.4 Identify widely used applications which use Sorting technique for implementation of
its important feature.
Sorting algorithms are foundational in computer science and are widely used in various applications. Here
are some notable applications:
92
Data Structure (3130702) 230160107100
1. Database Management: o Sorting is crucial for efficient querying and data retrieval. Indexing
in databases often involves sorting data to speed up search operations.
2. Data Analysis and Reporting:
o In analytics, sorting helps organize data for better interpretation and visualization. It’s common
to sort data by dates, values, or categories.
3. Search Algorithms: o Many search algorithms, like binary search, require sorted data to function
effectively.
Sorting is a prerequisite for these searches.
4. E-commerce Platforms: o Sorting is essential for product listings, allowing users to sort items
by price, rating, popularity, etc.
5. File Systems: o File systems often sort files and directories for efficient access and management,
such as displaying files in alphabetical order.
6. Graphics: o In computer graphics, sorting is used to determine the order in which objects are
rendered, especially in 3D graphics (z-ordering).
7. Machine Learning:
o Some machine learning algorithms, like k-means clustering, may require sorting data for
better performance and accuracy.
8. Scheduling: o Sorting is used in task scheduling algorithms to prioritize tasks based on certain
criteria like deadline, duration, or priority level.
9. Memory Management:
o In operating systems, sorting can help in memory allocation and managing free memory
blocks efficiently.
Conclusion:
Sorting algorithms are fundamental tools in computer science that organize data in a specific order, making
it easier to retrieve and analyze information efficiently. In this section, we implemented three widely-used
sorting algorithms: Quick Sort, Merge Sort, and Bubble Sort. Each algorithm has its strengths and
weaknesses, suitable for different scenarios depending on the dataset size and the required performance.
Quiz:
Sorting is the process of arranging the elements of a list or an array in a specified order, typically in
ascending or descending numerical or lexicographical order. The primary goal of sorting is to organize
data so that it can be efficiently searched, analyzed, or displayed. Common sorting methods include
Bubble Sort, Quick Sort, Merge Sort, and Insertion Sort, each with different algorithms and
performance characteristics.
93
Data Structure (3130702) 230160107100
(2) What is divide-and-conquer strategy for sorting?
The divide-and-conquer strategy is a fundamental algorithm design paradigm that works by recursively
breaking down a problem into smaller subproblems until they become manageable and can be solved
directly. In the context of sorting algorithms, this strategy involves three main steps:
1. Divide: The array or list is divided into two (or more) smaller subarrays. This process continues
recursively until each subarray contains only one element or is empty, which is considered a sorted
state.
2. Conquer: The smaller subarrays are sorted independently. Since a single-element array is
inherently sorted, this step often requires merging or combining the sorted subarrays back together.
3. Combine: The sorted subarrays are combined to form a single sorted array. This step typically
involves comparing the elements from each subarray and merging them in the correct order.
(3) Which is the best suitable sorting algorithm as per its execution time?
• Quick Sort is often considered the best choice for large datasets due to its average-case time
complexity of O(n log n) and its in-place sorting mechanism. It is very efficient for average cases and
widely used in practice.
• Merge Sort also has a time complexity of O(n log n) but requires additional space, making it less
suitable for environments with limited memory. However, it is stable and works well for linked lists.
• For small datasets, Insertion Sort may be faster despite its O(n²) time complexity because of its low
overhead and efficiency for nearly sorted data.
Suggested Reference:
94
Data Structure (3130702) 230160107100
Problem Coding Completeness
Logic
Understanding Standards and accuracy Q&A
Building (2)
Rubrics (2) (2) (2) Total
Avg. Good Avg. Good Avg. Good Avg. Good Avg. Good
(1) (2) (1) (2) (1) (2) (1) (2) (1) (2)
Marks
95
Data Structure (3130702) 230160107100
Experiment No: 10
AIM : Hashing and File Structure
10.1 Write a program to create hash table and handle the collision using linear probing.
10.2 Write a program to demonstrate the file primitives such as fopen, fclose, fprintf.
10.3 Identify widely used applications which use Hashing technique for implementation of
its important feature.
Date:
Theory:
Hashing
Hashing is a method used to map a large number of data items to a smaller table by utilizing a
hashing function. This technique transforms a range of key values into a range of indexes of an
array.There are two different forms of hashing.
1. Open hashing or external hashing: Open or external hashing, allows records to be stored in
unlimited space (could be a hard disk). It places no limitation on the size of the tables.
2. Close hashing or internal hashing: Closed or internal hashing, uses a fixed space for storage
and thus limits the size of hash table.
Hashing Functions
1. Division-Method
2. Folding Method
3. Algebraic Coding
4. Multiplicative Hashing
5. Digit Analysis
6. Mid-square Methods
7. Length Dependent Method
File
In computing, a file is a group of records, where each record comprises one or more fields that have the
same sequence. Typically, each field has a predetermined length.
1. Sequential files
2. Direct files
3. Index files
4. Indexed Sequential files
5. Relative files
1. Creation
2. Insertion
3. Deletion
4. Updation
5. Reading
6. Searching
97
Data Structure (3130702) 230160107100
10.1 Write a program to create hash table and handle the collision using linear probing.
Program:
#include <stdio.h>
#include <stdlib.h>
#define TABLE_SIZE 10
// Hash table
structure typedef
struct { int key; int
value;
} HashEntry;
HashEntry* hashTable[TABLE_SIZE];
// Main
function int
main() {
insert(10, 100);
insert(20, 200);
insert(30, 300);
insert(40, 400);
insert(25, 250); //
Collision
occurs, will use
linear probing
insert(5, 50);
displayHashTable();
return 0; }
Output:
10.2 Write a program to demonstrate the file primitives such as fopen, fclose, fprintf.
Program:
#include <stdio.h>
int main() {
FILE *filePointer;
99
Data Structure (3130702) 230160107100
// Open a file in write mode filePointer
= fopen("example.txt", "w"); if
(filePointer == NULL) { printf("Error
opening file!\n"); return 1;
}
char buffer[255];
// Read and display the content of the file
while (fgets(buffer, sizeof(buffer), filePointer) != NULL) {
printf("%s", buffer);
}
10.3 Identify widely used applications which use Hashing technique for implementation of
its important feature.
1. Database Indexing: Hashing is used to quickly locate a data record given its search key. It helps in
indexing databases for efficient data retrieval.
2. Caches: Hash tables are used in caching mechanisms to quickly retrieve data without searching
through all entries.
3. Symbol Tables: Compilers use hash tables to implement symbol tables for fast lookups of variable
names and their corresponding data.
100
Data Structure (3130702) 230160107100
4. Cryptography: Hash functions are crucial in security applications, such as password storage and
data integrity verification.
5. Memory Management: Operating systems use hashing techniques for managing memory blocks
efficiently, particularly in dynamic memory allocation.
6. Network Routing: Hashing algorithms are used in network routing protocols to determine the best
paths for data packets.
7. Distributed Systems: Hash tables are used in distributed systems for load balancing and
partitioning data across different nodes.
8. Text Processing: Hashing is used in algorithms for string matching, such as Rabin-Karp, to
efficiently find substrings.
Conclusion:
Hashing is a powerful technique used for efficient data retrieval and storage, allowing for quick access to
information through a calculated index. Internal and external hashing methods provide different ways to
manage hash tables, each with its advantages and use cases.
Quiz:
• Internal Hashing: In internal hashing, the hash table is stored in the main memory (RAM). This
method allows for faster access since the hash table resides in memory, leading to quicker retrieval
times. Internal hashing is typically used for smaller datasets that can fit into memory, and it
employs techniques like linear probing or chaining for collision resolution.
• External Hashing: External hashing involves storing the hash table on secondary storage (such as a
disk). This method is useful for larger datasets that do not fit into memory. External hashing can
utilize methods like overflow areas on disk to handle collisions and may involve more complex I/O
operations. While access times may be slower compared to internal hashing, it allows for handling
larger volumes of data efficiently.
Linear Probing is a collision resolution technique used in hash tables. When a new entry is
inserted into a hash table and the computed index (from the hash function) is already occupied,
linear probing searches for the next available index sequentially.
101
Data Structure (3130702) 230160107100
1. Open: This operation is used to create or access a file. It prepares the file for reading or
writing.
2. Close: This operation is used to terminate access to a file. It ensures that any changes made
to the file are saved and resources are released.
3. Read: This operation retrieves data from a file. It allows programs to access the contents
stored within the file.
4. Write: This operation allows data to be written to a file. It enables programs to store or
modify information in the file.
7. Flush: This operation ensures that any buffered data is written to the file, making it
immediately available.
Suggested Reference:
Marks
103