Data Structure LAB MANUAL 1 PDF
Data Structure LAB MANUAL 1 PDF
LIST OF EXPERIMENTS
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 2
Department of Computer Science & Engineering
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 3
Department of Computer Science & Engineering
INTRODUCTION
In computer science, data structure is a particular way of organizing and storing data in a
computer so that it can be accessed and modified efficiently. Precisely, it is a collection of
data values, the relationships among them, and the functions or operations that can be applied
to the data.
Data structures can implement one or more particular abstract data types (ADT), which
specify the operations that can be performed on a data structure and the computational
complexity of those operations. Usually, efficient data structures are the key to designing
efficient algorithms. The implementation of a data structure usually requires writing a set of
procedures that create and manipulate instances of that structure. The efficiency of a data
structure cannot be analyzed separately from those operations.
There are numerous types of data structures, generally built upon simpler primitive data
types:
An array is a number of elements in a specific order, typically all of the same type. Elements
are accessed using an integer index to specify which element is required. Typical
implementations allocate contiguous memory words for the elements of arrays (but this is not
always a necessity). Arrays may be fixed-length or resizable.
A linked list is a linear collection of data elements of any type, called nodes, where each node
has itself a value, and points to the next node in the linked list. The principal advantage of a
linked list over an array is that values can always be efficiently inserted and removed without
relocating the rest of the list. Certain other operations, such as random access to a certain
element, are however slower on lists than on arrays.
Data structures are generally based on the ability of a computer to fetch and store data at any
place in its memory, specified by a pointer—a bit string, representing a memory address, that
can be itself stored in memory and manipulated by the program. Thus, the array data
structures are based on computing the addresses of data items with arithmetic operations;
while the linked data structures are based on storing addresses of data items within the
structure itself.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 4
Department of Computer Science & Engineering
A data structure is said to be linear if its elements form a sequence or a linear list.
The linear data structures like an array, stacks, queues and linked lists organize data in linear
order.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 5
Department of Computer Science & Engineering
PREFACE
In order to develop efficient software systems, it is essential that efficient algorithms and
appropriate data structures are used. The purpose of this laboratory manual is to
introduce undergraduate students to techniques for developing efficient data structures and
algorithms in a systematic manner. The manual serves as a guide for learning and
implementing the linear and non-linear data structures in a programming language
(JAVA/C++). It basically focuses on memory management and various other operations on
data with algorithm analysis and design. The manual contains procedures, and pre-experiment
questions to help students prepare for experiments.
This practical manual will be helpful for students of Computer Science & Engineering for
understanding the course from the point of view of applied aspects. Though all the efforts
have been made to make this manual error free, yet some errors might have crept in
inadvertently. Suggestions from the readers for the improvement of the manual are most
welcomed.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 6
Department of Computer Science & Engineering
DO’s
DONT’S
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 7
Department of Computer Science & Engineering
1. Know the location of the fire extinguisher and the first aid box and how to use them in
case of an emergency.
4. Do not plug in external devices without scanning them for computer viruses.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 8
DATA STRUCTURES USING C/ JAVA LAB FILE (RCS 355)
Name
Roll No.
Section- Batch
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 16
Department of Computer Science & Engineering
INDEX
Experiment Experiment Date of Date of Faculty
No. Name Conduction Submission Signature
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 15
Department of Computer Science & Engineering
EXPERIMENT - 1
Description:
An array is data structures that are a collection of variables of same type that are accessed
through a common name. Following are important terms to understand the concepts of
Array.
• Index − each location of an element in an array has a numerical index which is used
to identify the element.
• Arrays can be declared in various ways in different languages. For illustration, let's
take C array declaration.
Pre-Experiment Questions:
Q3. What are the legal indexes for the array ar, given the following declaration:
int[] ar = {2, 4, 6, 8 }
a. 0, 1, 2, 3
b. 1, 2, 3, 4
c. 2, 4, 6, 8
d. 0, 2, 4, 6
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 16
Department of Computer Science & Engineering
Q4. Which of the following gives the memory address of the first element in array foo, an
array with 100 elements?
a. foo[0]
b. foo
c. &foo
d. foo[1]
Description: Here A is a two – dimensional array with M rows and N columns and B is a two
– dimensional array with X rows and Y columns. This algorithm adds these two arrays.
1. If (M ≠ X) or (N ≠ Y) Then
4. Repeat For I = 1 to M
5. Repeat For J = 1 to N
6. Set C[I][J] = A[I][J] + B[I][J] [End of Step 5 For Loop] [End of Step 6 For Loop]
7. Exit
Explanation: First, we have to check whether the rows of array A are equal to the rows of
array B or the columns of array A are equal to the columns of array B. if they are not equal,
then addition is not possible and the algorithm exits. But if they are equal, then first for loop
iterates to the total number of rows i.e. M and the second for loop iterates to the total number
of columns i.e. N. In step 6, the element A[I][J] is added to the element B[I][J] and is stored
in C[I][J] by the statement: C[I][J] = A[I][J] + B[I][J].
Description: Here A is a two – dimensional array with M rows and N columns and B is a two
– dimensional array with X rows and Y columns. This algorithm multiplies these two arrays.
1. If (M ≠ Y) or (N ≠ X) Then
3. Else
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 17
Department of Computer Science & Engineering
4. Repeat For I = 1 to N
5. Repeat For J = 1 to X
6. Set C[I][J] = 0
7. Repeat For K = 1 to Y
[End of If]
9. Exit
Explanation: First we check whether the rows of A are equal to columns of B or the columns
of A are equal to rows of B. If they are not equal, then multiplication is not possible. But, if
they are equal, the first for loop iterates to total number of columns of A i.e. N and the second
for loop iterates to the total number of rows of B i.e. X. In step 6, all the elements of C are set
to zero. Then the third for loop iterates to total number of columns of B i.e. Y. In step 8, the
element A[I][K] is multiplied with B[K][J] and added to C[I][J] and the result is assigned to
C[I][J] by the statement: C[I][J] = C[I][J] + A[I][K] * B[K][J].
Post-Experiment Questions:
int main()
{
int i;
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 18
Department of Computer Science & Engineering
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 19
Department of Computer Science & Engineering
EXPERIMENT - 2
Description:
Transpose of a 2D array is changing the rows of 2D array into columns and columns into
rows.
Transpose of a 2D array:
The below figure gives the representation of transpose operation performed on a 2D array,
Pre-Experiment Questions:
Q2. Given the base address of an array B[1300…..1900] as 1020 and size of each element is 2
bytes in the memory. Find the address of B[1700].
Let A is a two – dimensional array with M rows and N columns. This algorithm transposes
the array.
1. Repeat For I = 1 to M
2. Repeat For J = 1 to N
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 20
Department of Computer Science & Engineering
4. Exit
The first for loop iterates from 1 to M i.e. total number of rows and second for loop iterates
from 1 to N i.e. total number of columns. In step 3, the element at location A[I][J] is assigned
to B[J][I] by the statement B[J][I] = A[I][J].
Input:
Enter number of rows & columns of array : 3 x 3
Enter elements of 2-D array:
25 12 4 62 34 23 6 4 3
Output:
2-D array before transposing:
25 12 4
62 34 23
6 4 3
25 62 6
12 34 4
4 23 3
Post-Experiment Questions:
Q1. Let A be a square matrix of size n x n. Consider the following program. What is the
expected output?
C = 100;
for i = 1 to n do
for j = 1 to n do
{
Temp = A[i][j] + C
A[i][j] = A[j][i]
A[j][i] = Temp - C
}
for i = 1 to n do
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 21
Department of Computer Science & Engineering
for j = 1 to n do
Output(A[i][j]);
Q2. How to modify the program to find maximum element of each row in a matrix?
Q3. How to modify the program to print Lower triangular and Upper triangular matrix of an
array?
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 22
Department of Computer Science & Engineering
EXPERIMENT - 3
Stack Representation:
A stack can be implemented by means of Array (Static Implementation), and Linked list
(Dynamic implementation).
Stack operations may involve initializing the stack, using it and then de-initializing it. Apart
from these basic stuffs, a stack is used for the following two primary operations −
To use a stack efficiently, we need to check the status of stack as well. For the same purpose,
the following functionality is added to stacks −
peek() − get the top data element of the stack, without removing it.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 23
Department of Computer Science & Engineering
At all times, we maintain a pointer to the last PUSHed data on the stack. As this pointer
always represents the top of the stack, hence named top. The top pointer provides top value of
the stack without actually removing it.
Push Operation:
The process of putting a new data element onto stack is known as a Push Operation. Push
operation involves a series of steps −
If the linked list is used to implement the stack, then in step 3, we need to allocate space
dynamically.
Pop Operation:
Accessing the content while removing it from the stack, is known as a Pop Operation. In an
array implementation of pop() operation, the data element is not actually removed, instead top
is decremented to a lower position in the stack to point to the next value. But in linked-list
implementation, pop() actually removes data element and deallocates memory space.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 24
Department of Computer Science & Engineering
Step 3 − If the stack is not empty, accesses the data element at which top is pointing.
Step 4 − Decreases the value of top by 1.
Step 5 − Returns success.
Pre-Experiment Questions:
Q1. Explain Stack data structures.
Q3. Define the underflow and overflow conditions for stack operation.
Algorithms:
return stack[top]
end procedure
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 25
Department of Computer Science & Engineering
Input:
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 26
Department of Computer Science & Engineering
Output:
34
56
21
18
TOS=3
Post-Experiment Questions:
Q1. What is the advantage of dynamic implementation over static implementation of a stack?
Q2. What is the time complexity of push operation and pop operation?
Q3. Which one of the following is an application of Stack Data Structure?
a. Managing function calls
b. The stock span problem
c. Arithmetic expression evaluation
d. All of the above
Give an explanation for your answer.
Q4. Which of the following is true about linked list implementation of stack?
a. In push operation, if new nodes are inserted at the beginning of linked list, then in pop
operation, nodes must be removed from end.
b. In push operation, if new nodes are inserted at the end, then in pop operation, nodes
must be removed from the beginning.
c. Both of the above
d. None of the above
Give an explanation for your answer.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 27
Department of Computer Science & Engineering
EXPERIMENT - 4
Queue Representation
Same as Queue, queue can also be implemented using Array (Static Implementation),
Linked-list (Dynamic implementation)
Queue operations may involve initializing or defining the queue, utilizing it and then
completing erasing it from memory. There are two basic operations associated with queues −
Few more functions are required to make above mentioned queue operation efficient. These
are −
In queue, we always dequeue (or access) data, pointed by front pointer and while enqueing
(or storing) data in queue we take help of rear pointer.
isfull(): As we are using single dimension array to implement queue, we just check for the
rear pointer to reach at MAXSIZE to determine that queue is full. In case we maintain queue
in a circular linked-list, the algorithm will differ.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 28
Department of Computer Science & Engineering
Enqueue Operation:
As queue maintains two data pointers, front and rear, its operations are comparatively more
difficult to implement than Queue.
The following steps should be taken to enqueue (insert) data into a queue −
Sometimes, we also check that if queue is initialized or not to handle any unforeseen
situations.
Dequeue Operation:
Accessing data from queue is a process of two tasks − access the data wherefront is pointing
and remove the data after access. The following steps are taken to
perform dequeue operation −
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 29
Department of Computer Science & Engineering
Pre-Experiment Question:
Q2. What are the overflow and underflow conditions for operations on a Queue?
Algorithms:
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 30
Department of Computer Science & Engineering
Input:
1 45 78 90
Output:
23 1 45 78 90
Input:
23 1 45 78 90
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 31
Department of Computer Science & Engineering
Output:
23 1 45 78
Post-Experiment Questions
Q1. What is the advantage of dynamic implementation over static implementation of a queue?
Q2. What is the time complexity of enqueue operation and dequeue operation?
Q3. Which one of the following is an application of Queue Data Structure?
a. When a resource is shared among multiple consumers.
b. When data is transferred asynchronously (data not necessarily received at same rate as
sent) between two processes
c. Load Balancing
d. All of the above
Explain your answer.
Q4. Which of the following is true about linked list implementation of queue?
a. In push operation, if new nodes are inserted at the beginning of linked list, then in pop
operation, nodes must be removed from end.
b. In push operation, if new nodes are inserted at the end, then in pop operation, nodes must
be removed from the beginning.
c. Both of the above
d. None of the above
Explain your answer.
Q5. Suppose you are given an implementation of a queue of integers. The operations that can
be performed on the queue are:
i. isEmpty (Q) — returns true if the queue is empty, false otherwise.
ii. delete (Q) — deletes the element at the front of the queue and returns its value.
iii. insert (Q, i) — inserts the integer i at the rear of the queue.
Consider the following function:
void f (queue Q) {
int i ;
if (!isEmpty(Q)) {
i = delete(Q);
f(Q);
insert(Q, i);
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 32
Department of Computer Science & Engineering
}
}
What operation is performed by the above function f ?
a. Leaves the queue Q unchanged
b. Reverses the order of the elements in the queue Q
c. Deletes the element at the front of the queue Q and inserts it at the rear keeping the
other elements in the same order
d. Empties the queue Q
Explain your answer.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 33
Department of Computer Science & Engineering
EXPERIMENT – 5
Descriptions: Circular queue is a linear data structure. It follows FIFO principle. In circular
queue the last node is connected back to the first node to make a circle.Circular linked list
fallow the First In First Out principle. Elements are added at the rear end and the elements are
deleted at front end of the queue.
Pre-Experiment Questions:
Q1. What is the difference between queue and circular queue?
Q2. Suppose a circular queue of capacity (n – 1) elements is implemented with an array of n
elements. Assume that the insertion and deletion operation are carried out using REAR and
FRONT as array index variables, respectively. Initially, REAR = FRONT = 0. The conditions
to detect queue full and queue empty are .
Here QUEUE is an array with N locations. FRONT and REAR points to the front and rear
elements of the QUEUE. ITEM is the value to be inserted.
1. If (FRONT == 1 and REAR == N) or (FRONT == REAR + 1) Then
2. Print: Overflow
3. Else
4. If (REAR == 0) Then [Check if QUEUE is empty]
(a) Set FRONT = 1
(b) Set REAR = 1
5. Else If (REAR == N) Then [If REAR reaches end if QUEUE]
6. Set REAR = 1
7. Else
8. Set REAR = REAR + 1 [Increment REAR by 1] [End of Step 4 If]
9. Set QUEUE[REAR] = ITEM
10. Print: ITEM inserted [End of Step 1 If]
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 34
Department of Computer Science & Engineering
11. Exit
Input:
Insert element 7 in a circular queue
4 2 6 1 3 5
Output:
4 2 6 1 3 5 7
Post-Experiment Questions:
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 35
Department of Computer Science & Engineering
Q4. A circular queue is implemented using an array of size 10. The array index starts with 0,
front is 6, and rear is 9. The insertion of next element takes place at the array index .
Q5. If the MAX_SIZE is the size of the array used in the implementation of circular queue,
array index start with 0, front point to the first element in the queue, and rear point to the last
element in the queue. Which of the following condition specify that circular queue is
EMPTY?
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 36
Department of Computer Science & Engineering
EXPERIMENT - 6
Descriptions: The major problem with the stack implemented using array is, it works only
for fixed number of data values. That means the amount of data must be specified at the
beginning of the implementation itself. Stack implemented using 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 linked list data structure. The stack implemented using linked list can
work for unlimited number of values. That means, stack implemented using linked list works
for 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 as 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 next node in the list. The next field of the first element must be always NULL.
Pre-Experiment Questions:
Q1. Compare stack implementation by array and linked list.
Q2. What are the overflow and underflow conditions for different operations on stack using
linked list?
Algorithm for Inserting an element 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.
Step 4: If it is Not Empty, then set newNode → next = top.
Step 5: Finally, set top = newNode.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 37
Department of Computer Science & Engineering
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 38
Department of Computer Science & Engineering
EXPERIMENT - 7
Descriptions: The major problem with the queue implemented using array is, It will work
for only fixed number of data. That means, the amount of data must be specified in the
beginning itself. Queue using 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 linked list data
structure. The queue which is implemented using linked list can work for unlimited number
of values. That means, queue using linked list can work for variable size of data (No need to
fix the size at 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'.
In above example, the last inserted node is 50 and it is pointed by 'rear' and the first inserted
node is 10 and it is pointed by 'front'. The order of elements inserted is 10, 15, 22 and 50.
Pre-Experiment Questions:
Q1. The essential condition which is checked before insertion in a linked queue is?
Q2. The essential condition which is checked before deletion in a linked queue is?
Q3. Which of the following is true about linked list implementation of queue?
a. In push operation, if new nodes are inserted at the beginning of linked list, then in pop operation,
nodes must be removed from end
b. In push operation, if new nodes are inserted at the end, then in pop operation, nodes must be removed
from the beginning
c. Both a and b
d. None of the mentioned
Explain your answer.
Algorithm for enQueue(value) - Inserting an element 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.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 39
Department of Computer Science & Engineering
Step 4: If it is Not Empty then, set rear → next = newNode and rear = newNode.
Algorithm for deQueue() - Deleting an Element from Queue
Step 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)).
Post-Experiment Questions:
Q1. What is the time complexity for insertion in linked list implementation of queue?
Q2. In linked list implementation of queue, if only front pointer is maintained, which of the following
operation take worst case linear time?
a. Insertion
b. Deletion
c. To empty a queue
d. Both a and c
Explain your answer.
Q3. In linked list implementation of a queue, front and rear pointers are tracked. Which of these pointers will
change during an insertion into a NONEMPTY queue?
a. Only front pointer
b. Only rear pointer
c. Both front and rear pointer
d. None of the mentioned
Explain your answer.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 40
Department of Computer Science & Engineering
Q4. In linked list implementation of a queue, front and rear pointers are tracked. Which of these pointers will
change during an insertion into EMPTY queue?
a. Only front pointer
b. Only rear pointer
c. Both front and rear pointer
d. None of the mentioned
Explain your answer.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 41
Department of Computer Science & Engineering
EXPERIMENT - 8
Description: Circular Queue is a linear data structure in which the operations are performed
based on FIFO (First In First Out) principle and the last position is connected back to the first
position to make a circle. It is also called 'Ring Buffer'. In a normal Queue, we can insert
elements until queuebecomes full.
▪ enQueue(value) This function is used to insert an element into the circular queue. In a
circular queue, the new element is always inserted at Rear position.
▪ deQueue() This function is used to delete an element from the circular queue. In a
queue, the element is always deleted from front position.
Pre-Experiment Questions:
Q2. What is the major problem with the circular queue implemented using array?
Q3. What differentiates a circular linked list from a normal linked list?
Step1: Create a new node dynamically and insert value into it.
Step 2: Check if front==NULL, if it is true then front = rear = (newly created node)
Step3: If it is false then rare=(newly created node) and rear node always contains the address of the front node.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 42
Department of Computer Science & Engineering
Step 2: If it is empty then display Queue is empty. If queue is not empty then step 3
Step 3:Check if (front==rear) if it is true then set front = rear = NULL else move the front forward in queue,
update address of front in rear node and return the element.
Post-Experiment Questions:
Q2. Why it is better to use circular queue while using array implemention?
Q3. How do you count the number of elements in the circular linked list?
Q4. What is the time complexity of searching for an element in a circular linked list?
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 43
Department of Computer Science & Engineering
EXPERIMENT - 9
Descriptions: Binary tree is a special data structure used for data storage purposes. A binary
tree has a special condition that each node can have two children at maximum. Binary Search
tree exhibits a special behaviour. A node's left child must have value less than its parent's
value and node's right child must have value greater than it's parent value. A binary tree have
benefits of both an ordered array and a linked list as search is as quick as in sorted array and
insertion or deletion operation are as fast as in linked list.
• Root − Node at the top of the tree is called root. There is only one root per tree and
one path from root node to any node.
• Parent − Any node except root node has one edge upward to a node called parent.
• Child − Node below a given node connected by its edge downward is called its child
node.
• Leaf − Node which does not have any child node is called leaf node.
• Visiting − Visiting refers to checking value of a node when control is on the node.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 44
Department of Computer Science & Engineering
• Levels − Level of a node represents the generation of a node. If root node is at level
0, then its next child node is at level 1, its grandchild is at level 2 and so on.
Basic Operations
The basic operations that can be performed on binary search tree data structure, are
following −
then remove x
Pre-Experiment Questions
Q4. Write the pre-, post- and in-order traversal for the given tree.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 45
Department of Computer Science & Engineering
The very first insertion creates the tree. Afterwards, whenever an element is to be inserted.
First locate its proper location. Start search from root node then if data is less than key value,
search empty location in left subtree and insert the data. Otherwise search empty location in
right subtree and insert the data.
If root is NULL
return
else
endwhile
insert data
end If
Input:
4 2 6 1 3 5
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 46
Department of Computer Science & Engineering
Output:
4 2 6 1 3 5 7
2 then y z
3 else y Tree-Successor[z]
4. if left[y] NIL
5. then x left[y]
6. else x right[y]
7. if x NIL
9. if p[y] = NIL
14. if y z
16. return y
Post-Experiment Questions:
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 47
Department of Computer Science & Engineering
Q2. What must be the ideal size of array if the height of tree is ‘l’?
Q3. What is the time complexity for finding the height of the binary tree?
Q4. What are the children for node ‘w’ of a complete-binary tree in an array representation ?
Q5. What are the advantages and disadvantages of linked list representation of binary trees
over arrays?
Q6. What is the time complexity of pre-order traversal in the iterative fashion?
Q7. What is the space complexity of the post-order traversal in the recursive fashion? (d is the
tree depth and n is the number of nodes)
Q8. In a full binary tree if number of internal nodes is I, then number of leaves L are?
Q9. In a full binary tree if number of internal nodes is I, then number of nodes N are?
Q10. In a full binary tree if there are L leaves, then total number of nodes N are?
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 48
Department of Computer Science & Engineering
EXPERIMENT - 10
Description:Binary search is a fast search algorithm with run-time complexity of Ο(log n).
These search algorithms works on the principle of divide and conquer. For this algorithm to
work properly the data collection should be in sorted form. Binary search search a particular
item by comparing the middle most item of the collection. If match occurs then index of item
is returned. If middle item is greater than item then item is searched in sub-array to the right
of the middle item other wise item is search in sub-array to the left of the middle item. This
process continues on sub-array as well until the size of subarray reduces to zero.
Pre-Experiment Questions:
Q1. What is the difference between linear search and binary search?
node->left=insert(node->left,key);
elseif(key>node->key)
node->right=insert(node,right->key);
Post-Experiment Questions:
Q2. What is the worst case time complexity of search and insert operations in a BST?
Q3. What is the speciality about the inorder traversal of a binary search tree?
Q4. How will you find the minimum element in a binary search tree?
Q5. How will you find the maximum element in a binary search tree?
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 49
Department of Computer Science & Engineering
EXPERIMENT - 11
Description:Traversal is a process to visit all the nodes of a tree and may print their values
too. Because, all nodes are connected via edges (links) traversing always start from the root
(head) node. That is, why random access operation is not possible. There are three ways
which we use to traverse a tree −
• In-order Traversal
• Pre-order Traversal
• Post-order Traversal
Generally we traverse a tree to search or locate given item or key in the tree or to print all the
values it contains.
Inorder Traversal:
In this traversal method, the left left-subtree is visited first, then root and then the right sub-
tree. We should always remember that every node may represent a subtree itself. If a binary
tree is traversed inorder, the output will produce sorted key values in ascending order.
We start from A, and following in-order traversal, we move to its left subtree B.B is also
traversed in-ordered. And the process goes on until all the nodes are visited. The output of
in-order traversal of this tree will be −
D→B→E→A→F→C→G
Preorder Traversal:
In this traversal method, the root node is visited first, then left subtree and finally right sub-
tree.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 50
Department of Computer Science & Engineering
We start from A, and following pre-order traversal, we first visit A itself and then move to
its left subtree B. B is also traversed pre-ordered. And the process goes on until all the nodes
are visited. The output of pre-order traversal of this tree will be −
A→B→D→E→C→F→G
Postorder Traversal:
In this traversal method, the root node is visited last, hence the name. First we traverse left
subtree, then right subtree and finally root.
We start from A, and following pre-order traversal, we first visit left subtree B.B is also
traversed post-ordered. And the process goes on until all the nodes are visited. The output of
post-order traversal of this tree will be −
D→E→B→F→G→C→A
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 51
Department of Computer Science & Engineering
Input:
4 2 6 1 3 5 7
Output:
In-Order traversal: 4 2 6 1 3 5 7
Pre-Order traversal: 4 2 1 3 6 5 7
Post-Order traversal:1 3 2 5 7 6 4
Post-Experiment Questions
Q1. Which traversal algorithm traverses all the nodes of a binary tree in a sorted manner?
Q2.What is the time complexity of all traversing algorithms?
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 52
Department of Computer Science & Engineering
Q3. Which of the following pairs of traversals is not sufficient to build a binary tree from the
given traversals?
(A) Preorder and Inorder
(B) Preorder and Postorder
(C) Inorder and Postorder
(D) None of the Above
Q4. What does the following function do for a given binary tree?
int fun(struct node *root)
{
if (root == NULL)
return 0;
if (root->left == NULL && root->right == NULL)
return 0;
return 1 + fun(root->left) + fun(root->right);
}
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 53
Department of Computer Science & Engineering
EXPERIMENT - 12
q = new Queue();
q.enqueue(initial node);
while ( q ≠ empty ) do
{
x = q.dequeue();
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 54
Department of Computer Science & Engineering
{
visited[x] = true; // Visit node x !
Post-Experiment Questions:
Q1. A person wants to visit some places. He starts from a vertex and then wants to visit every
place connected to this vertex and so on. What algorithm he should use?
a) Depth First Search
b) Breadth First Search
c) Trim’s algorithm
d) None of the mentioned
Q2. The Breadth First Search traversal of a graph will result into?
a) Linked List
b) Tree
c) Graph with back edges
d) All of the mentioned
Q3. A person wants to visit some places. He starts from a vertex and then wants to visit every
place connected to this vertex and so on. What algorithm he should use?
Q4. In BFS, how many times a node is visited?
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 55
Department of Computer Science & Engineering
EXPERIMENT - 13
Pre-Experiment Questions:
Q1. Depth First Search is equivalent to which of the traversal in the Binary Trees?
Q2. When the Depth First Search of a graph is unique?
Q3. The Data structure used in standard implementation of Depth First Search is?
Q4. In Depth First Search, how many times a node is visited?
Algorithm for DFS:
n ← number of nodes
Initialize visited[ ] to false (0)
for(i=0;i<n;i++)
visited[i] = 0;
void DFS(vertex i) [DFS starting from i]
{
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 56
Department of Computer Science & Engineering
visited[i]=1;
for each w adjacent to i
if(!visited[w])
DFS(w);
}
Post-Experiment Questions:
Q1. Time Complexity of Depth First Search is? (V – number of vertices, E – number of
edges)
Q2. A person wants to visit some places. He starts from a vertex and then wants to visit every
vertex till it finishes from one vertex, backtracks and then explore other vertex from same
vertex. What algorithm he should use?
Q3. Regarding implementation of Depth First Search using stacks, what is the maximum
distance between two nodes present in the stack? ( considering each edge length 1)
Q4. What can be the applications of Depth First Search?
a) For generating topological sort of a graph
b) For generating Strongly Connected Components of a directed graph
c) Detecting cycles in the graph
d) All of the mentioned
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 57
Department of Computer Science & Engineering
EXPERIMENT - 14
Descriptions: Linear search is a very simple search algorithm. In this type of search, a
sequential search is made over all items one by one. Every item is checked and if a match
founds then that particular item is returned otherwise search continues till the end of the data
collection.
Pre-Experiment Questions:
Post-Experiment Questions:
Q1. Linear search is special case of which search?
Q3. What is the best case and worst case complexity of ordered linear search?
a) O(nlogn), O(logn)
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 58
Department of Computer Science & Engineering
b) O(logn), O(nlogn)
c) O(n), O(1)
d) O(1), O(n)
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 59
Department of Computer Science & Engineering
EXPERIMENT - 15
Description: Binary search is a fast search algorithm with run-time complexity of Ο(log n).
These search algorithms works on the principle of divide and conquer. For this algorithm to
work properly the data collection should be in sorted form. Binary search search a particular
item by comparing the middle most item of the collection. If match occurs then index of item
is returned. If middle item is greater than item then item is searched in sub-array to the right
of the middle item otherwise item is search in sub-array to the left of the middle item. This
process continues on sub-array as well until the size of subarray reduces to zero.
Pre-Experiment Question:
Set lowerBound = 1
Set upperBound = n
if A[midPoint] < x
set lowerBound = midPoint + 1
if A[midPoint] > x
set upperBound = midPoint - 1
if A[midPoint] = x
EXIT: x found at location midPoint
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 60
Department of Computer Science & Engineering
end while
end procedure
Input:
157289
Elements to be found: 8
Output:
Elements found at position no. 5
Post-Experiment Questions:
Q1. Binary Search can be categorized into which of the following?
a) Brute Force technique
b) Divide and conquer
c) Greedy algorithm
d) Dynamic programming
Q2. What is the time complexity of binary search with iteration?
Q3. Given an array arr = {45,77,89,90,94,99,100} and key = 100; What are the mid
values(corresponding array elements) generated in the first and second iterations?
a) 90 and 99
b) 90 and 100
c) 89 and 94
d) 94 and 99
Q4. Given an array arr = {5,6,77,88,99} and key = 88; How many iterations are done until the
element is found?
a) 1
b) 3
c) 4
d) 2
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 61
Department of Computer Science & Engineering
EXPERIMENT - 16
This is a in-place comparison based sorting algorithm. Here, a sub-list is maintained which is
always sorted. For example, the lower part of an array is maintained to be sorted. A element
which is to be 'insert'ed in this sorted sub-list, has to find its appropriate place and insert it
there. Hence the name insertion sort. The array is searched sequentially and unsorted items
are moved and inserted into sorted sub-list (in the same array). This algorithm is not suitable
for large data sets as its average and worst case complexity are of Ο(n 2) where n are no. of
items.This process goes until all the unsorted values are covered in sorted sublist.
Pre-Experiment Questions:
Q1. What is the difference between stable sort and unstable sort?
Q2. List out the stable sorting algorithms.
Q3. List out the unstable sorting algorithms.
Q4. What is the advantage of bubble sort over other sorting techniques?
We assume list is an array of n elements. We further assume that swap function, swaps the
values of given array elements.
begin BubbleSort(list)
for all elements of list
if list[i] > list[i+1]
swap(list[i], list[i+1])
end if
end for
return list
end BubbleSort
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 62
Department of Computer Science & Engineering
Post-Experiment Questions:
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 63
Department of Computer Science & Engineering
EXPERIMENT - 17
Description: Selection sort is a simple sorting algorithm. This sorting algorithm is a in-place
comparison based algorithm in which the list is divided into two parts, sorted part at left end
and unsorted part at right end. Initially sorted part is empty and unsorted part is entire
list.Smallest element is selected from the unsorted array and swapped with the leftmost
element and that element becomes part of sorted array. This process continues moving
unsorted array boundary by one element to the right. This algorithm is not suitable for large
data sets as its average and worst case complexity are of O(n2) where n are no. of items.
Pre-Experiment Questions:
Post-Experiment Questions:
Q1. What is the advantage of selection sort over other sorting techniques?
a) It requires no additional storage space
b) It is scalable
c) It works best for inputs which are already sorted
d) It is faster than any other sorting technique
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 64
Department of Computer Science & Engineering
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 65
Department of Computer Science & Engineering
EXPERIMENT - 18
Pre-Experiment Question:
Q1. Which is the correct order of the following algorithms with respect to their time
Complexity in the best case ?
a) Merge sort > Quick sort >Insertion sort > selection sort
b) insertion sort < Quick sort < Merge sort < selection sort
c) Merge sort > selection sort > quick sort > insertion sort
d) Merge sort > Quick sort > selection sort > insertion sort
Q2. Consider the array A[]= {6,4,8,1,3} apply the insertion sort to sort the array . Consider
the cost associated with each sort is 25 rupees , what is the total cost of the insertion sort
when element 1 reaches the first position of the array ?
a) 50
b) 25
c) 75
d) 100
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 66
Department of Computer Science & Engineering
PostExperiment Question:
Q1. Consider an array of elements arr[5]= {5,4,3,2,1} , what are the steps of insertions done
while doing insertion sort in the array.
a) 4 5 3 2 1 3 4 5 2 1 2 3 4 5 1 1 2 3 4 5
b) 5 4 3 1 2 5 4 1 2 3 5 1 2 3 4 1 2 3 4 5
c) 4 3 2 1 5 3 2 1 5 4 2 1 5 4 3 1 5 4 3 2
d) 4 5 3 2 1 2 3 4 5 1 3 4 5 2 1 1 2 3 4 5
Q2. Which sorting algorithm will take least time when all elements of input array are
identical? Consider typical implementations of sorting algorithms.
a)Insertion Sort
b)Heap Sort
c)Merge Sort
d) Selection Sort
Q3. If all the elements in an input array is equal for example {1,1,1,1,1,1}, What would be the
running time of the Insertion Algorithm?
Q4. What operation does the Insertion Sort use to move numbers from the unsorted section to
the sorted section of the list?
a) Finding the minimum value
b) Swapping
c) Finding out an pivot value
d) None of the above
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 67
Department of Computer Science & Engineering
EXPERIMENT - 19
Description: Merge sort first divides the array into equal halves and then combines them in a
sorted manner. Merge sort keeps on dividing the list into equal halves until it can no more be
divided. By definition, if it is only one element in the list, it is sorted. Then merge sort
combines smaller sorted lists keeping the new list sorted too. Merge sort is a sorting
technique based on divide and conquer technique. With worst-case time complexity being
Ο(n log n).
Pre-Experiment Question:
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 68
Department of Computer Science & Engineering
Post-Experiment Question:
b) Heap Sort
c) Merge Sort
d) Selection Sort
Q4. Which of the following is true about merge sort?
a) Merge Sort works better than quick sort if data is accessed from slow sequential memory.
b) Merge Sort is stable sort by nature
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 69
Department of Computer Science & Engineering
EXPERIMENT - 20
Pre-Experiment Questions:
Q1. In a max-heap, element with the greatest key is always in which node?
Q2.Heap can be used as……
a)Priority queue b)Stack
c)Adecreasingorderarray
d) None of the mentioned
Q3.What is the space complexity of searching in a heap?
Q4. What is the best case complexity in builading a heap?
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 70
Department of Computer Science & Engineering
}
}
Post-Experiment Questions:
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 71
Department of Computer Science & Engineering
EXPERIMENT - 21
These rings are of different sizes and stacked upon in an ascending order, i.e. the smaller one
sits over the larger one. There are other variations of the puzzle where the number of disks
increase, but the tower count remains the same.
Rules: The mission is to move all the disks to some another tower without violating the
sequence of arrangement. A few rules to be followed for Tower of Hanoi are −
• Only one disk can be moved among the towers at any given time.
• Only the "top" disk can be removed.
• No large disk can sit over a small disk.
Following is an animated representation of solving a Tower of Hanoi puzzle with three disks.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 72
Department of Computer Science & Engineering
Tower of Hanoi puzzle with n disks can be solved in minimum 2n−1 steps. This presentation
shows that a puzzle with 3 disks has taken 23 - 1 = 7 steps.
Pre-Experiment Questions:
Q1. Which data structure can be used suitably to solve the Tower of Hanoi problem?
a) Tree
b) Heap
c) Priority queue
d) Stack
Algorithm:
o write an algorithm for Tower of Hanoi, first we need to learn how to solve this problem
with lesser amount of disks, say → 1 or 2. We mark three towers with name, source,
destination and aux (only to help moving the disks). If we have only one disk, then it can
easily be moved from source to destination peg.
If we have 2 disks −
• First, we move the smaller (top) disk to aux peg.
• Then, we move the larger (bottom) disk to destination peg.
• And finally, we move the smaller disk from aux to destination peg.
So now, we are in a position to design an algorithm for Tower of Hanoi with more than two
disks. We divide the stack of disks in two parts. The largest disk (nth disk) is in one part and
all other (n-1) disks are in the second part.
Our ultimate aim is to move disk n from source to destination and then put all other (n1) disks
onto it. We can imagine to apply the same in a recursive way for all given set of disks.
The steps to follow are −
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 73
Department of Computer Science & Engineering
Post-Experiment Questions:
Q1. What is the number of moves required in the Tower of Hanoi problem for k disks?
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 74
Department of Computer Science & Engineering
EXPERIMENT - 22
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 75
Department of Computer Science & Engineering
Pre-Experiment Questions:
Q1. Fill the table with operator precedence and associativity (highest to lowest) −
Sr.No. Operator Precedence Associativity
1 Exponentiation ^
2 Multiplication ( ∗ ) & Division ( / )
3 Addition ( + ) & Subtraction ( − )
Q2. Which data structure is used to convert infix notations to pre and postfix notations?
Algorithm to convert an infix notation to Postfix notation:
1. Scan the infix expression from left to right.
2. If the scanned character is an operand, output it.
3. Else,
…..3.1 If the precedence of the scanned operator is greater than the precedence of the
operator in the stack(or the stack is empty), push it.
…..3.2 Else, Pop the operator from the stack until the precedence of the scanned operator is
less-equal to the precedence of the operator residing on the top of the stack. Push the scanned
operator to the stack.
4. If the scanned character is an ‘(‘, push it to the stack.
5. If the scanned character is an ‘)’, pop and output from the stack until an ‘(‘ is encountered.
6. Repeat steps 2-6 until infix expression is scanned.
7. Pop and output from the stack until it is not empty.
Post-Experiment Questions:
Q1. Why postfix representation of the expression?
Q2. Convert the following infix notation to post and prefix notations using stack.
a+b*(c^d-e)^(f+g*h)-i
Q3. What is the timecomplexity of the algorithm to convert infix notation to pre and postfix
notation?
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 76
Department of Computer Science & Engineering
EXPERIMENT - 23
Description: Prefix and Postfix expressions can be evaluated faster than an infix expression.
This is because we don’t need to process any brackets or follow operator precedence rule. In
postfix and prefix expressions which ever operator comes before will be evaluated first,
irrespective of its priority. Also, there are no brackets in these expressions. As long as we can
guarantee that a valid prefix or postfix expression is used, it can be evaluated with
correctness.
Postfix Evaluation Algorithm:
4. Start scanning the string from the right one character at a time.
6. If it is an operator, pop opnd1, opnd2 and perform the operation, specified by the
operator. Push the result in the stack.
Input : -+8/632
Output : 8
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 77
Department of Computer Science & Engineering
Input: 231*+9-
Output : -4
Post-Experiment Questions:
Q1. Evaluate the postfix notation 2 3 1 * + 9 – using the implemented algorithm. Show all the
steps.
Q2. Evaluate the postfix notation - + 8 / 6 3 2 using the implemented algorithm. Show all the
steps.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 78
Department of Computer Science & Engineering
References
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 79
Department of Computer Science & Engineering
APPENDIX
AKTU SYLLABUS
2. To transpose a 2D array.
Data Structures Using C/ Java Lab (RCS-355) Manual (CS, III SEM) Page 80