0% found this document useful (0 votes)
23 views46 pages

Lab Manual DS

Data Structure

Uploaded by

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

Lab Manual DS

Data Structure

Uploaded by

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

Data Structures

Course Code CC-6313

Laboratory Manual

Department of Computer Science


Lahore Garrison University
Main Campus, Sector-C Phase-VI, DHA Lahore

1|P a g e
Guidelines for Laboratory Procedure

The laboratory manual is the record of all work on your experiments. A complete, neat, and

organized data record is as important as the experiment itself. Please follow these guidelines for

efficient performance in the laboratory:

1. Attend the lab orientation to familiarize yourself with the lab setup.

2. Follow the designated lab schedule and complete assignments on time.

3. Write clear and well-documented code, avoiding plagiarism and unauthorized collaboration.

4. Seek help from lab instructors or peers if you encounter difficulties with programming concepts.

5. Regularly back up your code and project files to prevent data loss.

6. Use lab resources responsibly, including computers and software licenses.

7. If collaboration is allowed, work effectively with peers, ensuring each member contributes

meaningfully.

8. Maintain a clean and organized workspace for better focus and efficiency.

9. Thoroughly test your code to identify and fix errors before submission.

10. Engage in lab discussions, share insights, and actively participate to enhance the learning

experience.

2|P a g e
Safety Precautions

1. Handle equipment carefully to prevent damage and avoid placing liquids near electronic devices.

2. Maintain an ergonomic workspace for comfortable and strain-free programming.

3. Save work frequently and use surge protectors to prevent data loss due to power issues.

4. Keep software and antivirus programs up to date and avoid downloading from untrusted sources.

5. Regularly back up code and important files to prevent data loss.

6. Establish clear communication and collaboration guidelines when working with others.

7. Be aware of emergency exits, fire extinguisher locations, and evacuation procedures.

3|P a g e
Safety Undertaking

I have read all of the above, and I agree to conform to its contents.

Name:

Registration No.:

Student Signature:

Date:

Lab Instructor:

4|P a g e
Practical No. Title Page
CLO No.
Arrays Operation
1 3 6

2 Linear Search Algorithm


3 8

3 Binary Search Algorithm


3 12

4 Application of Stack
3 15

5 Single Linked List


3 19

6 Double Linked List


3 22

7 Queues Implementation
3 24

8 Recursive Sort
3,4 26

9 Binary Search Tree


4 29

10 AVL Tree
4 31

11 Heap Data Structure


4 34

12 Graph
4 39

13 Graph MST
4 43

14 DJIKSTRA algorithm
3 45

5|P a g e
PRACTICAL NO.01
Arrays Operation
PLO CLO LL
4 3 C-3
OBJECTIVE:
To review the concept of arrays and their declaration in C++.
To implement basic operations on arrays such as insertion, deletion, and updating of elements.
To implement algorithms for array manipulation.
Theory Overview
An array is a data structure that stores a collection of elements, each identified by at least one
array index or key. It is a contiguous area of memory consisting of elements of the same type.
Declaration: In C++, arrays are declared using the syntax type name [size]; , where type is the
data type of the elements, name is the name of the array, and size is the number of elements in
the array.
Initialization: Arrays can be initialized at the time of declaration or later using a loop or by
assigning values to individual elements.
Accessing Elements: Elements of an array are accessed using their index. The index starts from
0 for the first element and goes up to size-1 for the last element.
Array Operations
Insertion
Deletion
Updating:
Traversal:
Searching:
Sorting:
Merging:
Applications: Arrays are used in various applications such as storing and processing data in
databases, implementing matrices, representing images, and in many algorithms and programs.

6|P a g e
Data Structures
Department of Computer Science, LGU

TASK 1:
Perform all operations of array using functional approach.

CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
Data Analysis 5 5
& Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

7|P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.02
Linear Search Algorithm
PLO CLO LL
4 3 C-3
OBJECTIVE:

To understand the concept of linear search and its basic implementation. To implement the
linear search algorithm to search for a key element in an array. To analyze the time
complexity of linear search and understand its efficiency for different sizes of arrays. To
apply linear search in practical scenarios such as searching for an element in a list of student
records or a database.
To illustrate the concept of worst-case, best-case, and average-case scenarios for linear search
and how they relate to the position of the key element in the array.

Theory Overview

Concept of Linear Search: Linear search is a simple search algorithm that sequentially
checks each element in a collection until a match is found or the whole collection has been
searched. It is also known as a sequential search.

Basic Implementation of Linear Search


• Start from the first element of the array.
• Compare the key element with each element of the array sequentially.
• If the key element matches any element, return the index of that element.
• If the key element is not found after checking all elements, return a specific value
(e.g., -1) to indicate that the element is not in the array.

Time Complexity Analysis


Worst-case
If the key element is not present in the array or is present at the last position, the algorithm
will have to check all n elements. The worst-case time complexity is O(n).
Best-case
If the key element is found at the first position, the algorithm will perform only one
comparison. The best-case time complexity is O(1).
Average-case
On average, the algorithm will have to check half of the n elements. The average-case time
complexity is O(n/2), which simplifies to O(n).
Efficiency for Different Sizes of Arrays
Linear search is straightforward and easy to implement, but it is not efficient for large
datasets. As the size of the array increases, the time taken for linear search also increases
linearly.
Practical Application in Student Records or Databases
Linear search can be applied to search for a student's record in a list of student records or to
search for a specific entry in a database.
For example, in a student database, linear search can be used to find a student's details based
on their student ID or name.
Illustration of Worst-case, Best-case, and Average-case Scenarios

8|P a g e
Data Structures
Department of Computer Science, LGU

The worst-case scenario occurs when the key element is not present in the array or is present
at the last position, requiring n comparisons.
The best-case scenario occurs when the key element is found at the first position, requiring
only one comparison.
The average-case scenario occurs when the key element is found in the middle of the array,
requiring approximately n/2 comparisons on average.
Example

You are tasked with developing a program for managing a library's book inventory using
C++. The program should provide functionality for various array operations to handle the
book records efficiently. Here's the scenario you need to base your question on:
Scenario Description:
You are a software developer working for a library. The library needs a software tool to
manage its book inventory efficiently. Your task is to design a C++ program that allows
librarians to perform various array operations on the book inventory. The program should
include functionalities for traversing the book records, inserting new books, deleting existing
books, searching for specific books, and updating book information.
Question:
Develop a C++ program to manage the book inventory for the library. Implement the
following array operations:
Traverse Operation:
Write a function to display all the books currently in the inventory.
Insertion:
Implement a function that allows the librarian to add a new book to the inventory. The
function should prompt the user to enter the details of the new book (e.g., title, author, ISBN),
and then add it to the inventory.
Deletion:
Create a function to remove a book from the inventory based on the given book title or ISBN.
The function should prompt the user to enter the title or ISBN of the book they want to delete
and then remove it from the inventory.
Searching:
Write a function to search for a book in inventory based on either the book's title or ISBN.
The function should prompt the user to enter the title or ISBN of the book they want to search
for and then display the book details if found.
Update:
Implement a function to update the information of a book in the inventory. The function
should prompt the user to enter the title or ISBN of the book they want to update, and then
allow them to modify any information related to that book (e.g., title, author, ISBN)
Ensure that your program provides a user-friendly interface with clear instructions for each
operation. Test your program with sample inputs to demonstrate its functionality.

9|P a g e
Data Structures
Department of Computer Science, LGU

TASK 1:
Scenario:
You are developing a student management system for a school using C++. The system should
allow teachers to perform various array operations on student records to efficiently manage
their academic information. Here's the scenario you need to base your question on:
Scenario Description:
You are tasked with creating a C++ program to help teachers manage student records for a
school. The program should provide functionalities for teachers to perform array operations
on the student data, including traversing the list of students, inserting new student records,
deleting existing student records, searching for specific students, and updating student
information.
Question:
Develop a C++ program for managing student records in a school. Implement the following
array operations:
Traverse Operation:
Write a function to display the details of all the students currently enrolled in the school.
Insertion:
Implement a function that allows teachers to add a new student record to the system. The
function should prompt the teacher to enter the student's details (e.g., name, roll number,
grade), and then add it to the student records.
Deletion:
Create a function to remove a student record from the system based on the given roll number
or name. The function should prompt the teacher to enter the roll number or name of the
student they want to delete and then remove the corresponding record from the system.
Searching:
Write a function to search for a student in the records based on either the student's roll
number or name. The function should prompt the teacher to enter the roll number or name of
the student they want to search for and then display the student details if found.
Update:
Implement a function to update the information of a student in the records. The function
should prompt the teacher to enter the roll number or name of the student they want to
update, and then allow them to modify any information related to that student (e.g., name,
grade, contact information).
Ensure that your program provides a user-friendly interface with clear instructions for each
operation. Test your program with sample inputs to demonstrate its functionality.

10 | P a g e
Data Structures
Department of Computer Science, LGU

CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
Data Analysis 5 5
& Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

11 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.03
Binary Search Algorithm
PLO CLO LL
4 3 C-3
OBJECTIVE:
Understand and implementing the concept of binary search algorithm iteratively.
Demonstrate how to apply binary search to search for an element in a sorted array. Discuss
the limitations of binary search. Illustrate the step-by-step process of binary search with
examples. Implement binary search in a practical programming problem or application.

Theory Overview
Binary search is an efficient algorithm for finding a target value within a sorted array. It
works by repeatedly dividing the search interval in half. If the value of the target is less than
the middle element of the interval, the search continues in the lower half. If the value is
greater, the search continues in the upper half. This process is repeated until the target value
is found or the interval is empty.
Iterative Approach
1. Elements in array must be sorted.
2. Divide the array into two parts.
3. Use variables mid, start and end.
4. Where start = 0 and end = no of elements – 1.
5. For searching use while loop.
6. Set the value of mid = start + end / 2.
7. Compare the element on mid index with target value.
8. If matched display found else compare it with the element present on start and end
index.
9. If the element on mid index is smaller than target value than start = mid + 1.
10. If the element on mid index is greater than target value than end = mid - 1.
11. Repeat step 6-10 until the match is found.

Time Complexity
Binary search has a time complexity of O(log n), where n is the number of elements in the
array. This makes it significantly more efficient than linear search (O(n)), especially for large
arrays.

Applications
Binary search is commonly used in scenarios where the data is sorted and efficient searching
is required. It is used in various applications such as searching in databases, finding elements
in sorted arrays, and more.

Limitations
Binary search requires the array to be sorted, which can add an additional overhead if the
array is frequently modified.
It may not be suitable for small arrays or unsorted data, as the overhead of sorting or
maintaining a sorted array may outweigh the benefits of binary search.

12 | P a g e
Data Structures
Department of Computer Science, LGU

Comparisons
Linear Search: Binary search is more efficient than linear search for large arrays, as it has a
lower time complexity.
Conclusion
Binary search is a powerful algorithm for efficiently finding elements in a sorted array.
Understanding its implementation and limitations can help in applying it effectively to
various problem-solving scenarios.

13 | P a g e
Data Structures
Department of Computer Science, LGU

TASK 1:
Design a game that asks the user to guess a no within a specific range and then the program
will guess that number :(Hint! Use Binary search)

TASK 2:

You are working on a project to develop a simple phone book application. The application
stores contact information such as name, phone number and address. You decide to
implement a search feature using the binary search algorithm to efficiently find contact
information based on the name.
Question: Given an array of contacts sorted alphabetically by name, write a function in C++
to perform a binary search to find the contact information for a given name. Define the
structure/ class for a contact that includes the name and phone number. Also, discuss the time
complexity of the binary search algorithm in this scenario.

CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
Data Analysis 5 5
& Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

14 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.04
Application of Stack

PLO CLO LL
4 3 C-3
OBJECTIVE:
Understand the applications of stacks.
Implement stacks using both static and dynamic implementation.
Theory Overview
Stack is a memory portion, which is used for storing the elements. The elements are stored
based on the principle of LIFO (Last In, First Out). In stack insertion and deletion of elements
take place at the same end (Top). The last element inserted will be the first to be retrieved.
• This end is called Top
• The other end is called Bottom

Top: The stack top operation gets the data from the top-most position and returns it to the
user without deleting it. The underflow state can also occur in stack top operation if stack is
empty.
Push: The push operation adds a new element to the top of the stack or initializes the stack if
it is empty. If the stack is full and does not contain enough space to accept the given item, the
stack is then considered to be in an overflow state.
Pop: The pop operation removes an item from the top of the stack. A pop either returns
previously inserted items, or NULL if stack is empty.
Underflow: When stack contains equal number of elements as per its capacity and no more
elements can be added, the status of stack is known as overflow.
Stacks can be implemented using arrays or linked lists.
Arrays are simpler but have a fixed size, while linked lists can grow dynamically but require
more memory per element.

15 | P a g e
Data Structures
Department of Computer Science, LGU

Time Complexity
The time complexity of push, pop, peek, isEmpty, and size operations is O(1) for both array
and linked list implementations.

16 | P a g e
Data Structures
Department of Computer Science, LGU

Task 1
Write a program using stack operations, which accepts a non-negative base 10 integer as a
parameter, and display binary representation of number.
Description: To convert a number from decimal to binary, you simply divide by two and push
reminder to stack until quotient is reached to zero, then use pop operation to display the
binary representation of number. For example, to convert (35)10 to binary, you perform the
following computation.
35/2 = 1
17/2 = 1
8/2 = 0
4/2 = 0
2/2 = 0
1
If you examine the remainders from the last division to the first one, writing them down as
you go, you will get the following sequence: 100011. i.e. (100011)2 = (35)10
Task 2:
Write c++ program to take a string expression as input from user. Using this infix expression,
you must convert it into its equivalent postfix notation.

17 | P a g e
Data Structures
Department of Computer Science, LGU

CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
5 5
Data Analysis &
Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

18 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.5
SINGLY LINKED LIST
Objectives:
(a). Understand the concepts of singly linked lists
(b). Implement singly linked list using dynamic structures
Theory Overview:
Linked Lists: A linked list is a data structure consisting of a group of nodes which together
represent a sequence. Under the simplest form, each node is composed of a datum and a
reference (in other words, a link) to the next node in the sequence; more complex variants
add additional links. This structure allows for efficient insertion or removal of elements from
any position in the sequence.

Insertion: To insert data in a linked list, a record is created holding the new item. The
nextpointer of the new record is set to link it to the item which is to follow it in the list. The
nextpointer of the item which is to precede it must be modified to point to the new item.

Deletion: To deleted data from list, The nextpointer of the item immediately preceding the
one to 6. be deleted is altered and made to point to the item following the deleted item.

19 | P a g e
Data Structures
Department of Computer Science, LGU

20 | P a g e
Data Structures
Department of Computer Science, LGU

Task 1:
Write a program to display string using linked list. Take a string of character from user and
split the string in character, and then insert each character into linked list.

Task 2:
Consider a scenario where a firm wants to maintain the data of its employees. The data
containing employee number, name, and salary and department # are saved in a singly linked
list. Create following functions for the employee list.
InsertAtFront: Insertion of a record at the front.
InsertAtEnd: Insertion of a record at the end.
Insert: Insertion of a record at any position in the list
DeleteFirst: Deletion of first record.
DeleteLast: Deletion of last record.
Delete: Deletion of a record at any position in the list.
Search: Searching any record based on employee number and dept no.
Display: Displaying all records.

Task 3:
Write a program to split a single linked list in two separate lists and display both lists.

CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
5 5
Data Analysis &
Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

21 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.06
Double Linked List
PLO CLO LL
4 3 C-3
OBJECTIVE:

Understanding the concepts and operations of doubly linked lists.


Implement doubly linked list using dynamic structures.
Theory Overview
Doubly Linked Lists: A doubly linked list is a data structure consisting of a group of nodes
which together represent a sequence and are connected to each other in both directions (Bi-
directional). In Doubly linked list, each node has two pointers. One pointer to its successor
(NULL if there is none) and one pointer to its predecessor (NULL if there is none) which
enables bi-directional traversing.

Insertion: To insert data in a doubly linked list, a record is created holding the new item. The
next pointer of the new record is set to link it to the item which is to follow it in the list. The
pre-pointer of the new record is set to link it to the item which is to before it in the list.

Deletion: In deletion process, element can be deleted from three different places. When the
node is deleted, the memory allocated to that node is released and the previous and next
nodes of that node are linked.

22 | P a g e
Data Structures
Department of Computer Science, LGU

Task 1:
Write a menu driven program to perform insertion, deletion and display functions for doubly
linked list.

Task 2:
write a function MoveToFront( ) with one argument of data type integer. This function will
first search the linked list and compare the Data member of the node with the given number
as argument. If the search finds the number in the list then this function will move that node
to the start of the list as shown in the example below. The order of the remaining nodes is to
remain unchanged. If no node in the list contains the integer, MoveToFront( ) should leave
the list unchanged.
Assume that the list contains no duplicate values.

CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtaine Marks Obtained
d
Ability to 5 5
Conduct Structure
practical
Data Analysis 5 5
&
Efficiency
Interpretatio
n
Total Marks obtained Total Marks Obtained

23 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.07
QUEUES – DYNAMIC IMPLEMENTATION
PLO CLO LL
4 3 C-3
OBJECTIVE:
To understand and implement the concepts of queues using data structures (b). To learn
priority queue and its implementation
Theory Overview
Queue: A queue is a particular kind of collection in which the entities in the collection are
kept in order and the principal (or only) operations on the collection are the addition of
entities to the rear terminal position and removal of entities from the front terminal position.
This makes the queue a First-In First-Out (FIFO) data structure. In a FIFO data structure, the
first element added to the queue will be the first one to be removed. This is equivalent to the
requirement that once an element is added, all elements that were added before have to be
removed before the new element can be invoked. A queue is an example of a linear data
structure.

Static: Queue is implemented by an array, and size of queue remains fix


Dynamic: A queue can be implemented as a linked list, and expand or shrink with each
enqueue or dequeue operation.

Enqueue: Enqueue ( ) operation adds a new item to the end of the queue, or initializes the
queue if it is empty.
Dequeue: Dequeue ( ) operation removes an item from the front of the queue. A Dequeue
operation on an empty stack results in an underflow.

24 | P a g e
Data Structures
Department of Computer Science, LGU

Task 1:
Write a menu driven program to perform different operations with queue such Enqueue ( ),
Dequeue( ) and DisplayQueue( ).
Task 2:
You must take a single string as input. Using this input string, you have to create multiple
queues in which each queue will comprise of separate word appeared in input string. At the
end, you will again concatenate all queues to a single queue.
Example:

CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
5 5
Data Analysis &
Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

25 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.08
Recursive Sort

OBJECTIVE: PLO CLO LL


Understanding the concepts of recursion and its practical usage
5 4 C-3
Implementation of recursion
Theory Overview:

Recursion: Recursion is a programming technique in which procedures and functions call


themselves. When a function calls itself, it is making a recursive call. This approach can be
applied to solve many types of problems. Most computer programming languages support
recursion by allowing a function to call itself within the program.
Recursive Call:A function call in which the function being called is the same as the one
making the call. Base Case: • The case for which the solution can be stated non-recursively •
The case for which the answer is explicitly known. Recursive Case:A recursive function
definition also contains one or more recursive cases; meaning input(s) for which the program
recurs (calls itself). The job of the recursive cases can be seen as breaking down complex
inputs into simpler ones. In a properly-designed recursive function, with each recursive call,
the input problem must be simplified in such a way that eventually the base case must be
reached. For example, the factorial function can be defined recursively by the equations 0! =
1 and, for all n > 0, n! = n (n − 1)! None of equation by itself constitutes a complete
definition, the first is the base case, and the second is the recursive case.
Recursive Sort
Recursive Sort includes Merge sort and Quick sort
Quick Sort

Concept: Quick Sort is a divide-and-conquer algorithm that works by selecting a 'pivot'


element from the array and partitioning the other elements into two sub-arrays according to
whether they are less than or greater than the pivot. The sub-arrays are then sorted
recursively.

Steps:

1. Choose a pivot element from the array.


2. Rearrange the elements so that all elements less than the pivot are on the left, and all
elements greater than the pivot are on the right.
3. Recursively apply the above steps to the sub-array of elements with smaller values
and separately to the sub-array of elements with greater values.

Merge Sort

Concept: Merge Sort is also a divide-and-conquer algorithm that works by dividing the array
into two halves, sorting each half, and then merging the sorted halves to produce a sorted
array.

Steps:

26 | P a g e
Data Structures
Department of Computer Science, LGU

1. Divide the array into two halves.


2. Recursively sort each half.
3. Merge the two sorted halves into a single sorted array.

27 | P a g e
Data Structures
Department of Computer Science, LGU

Task 1:
Imagine you are a software developer working for an e-commerce company. The company
needs to optimize its product recommendation system by sorting products based on their
customer ratings. The product ratings are represented as an array of integers where each
integer indicates the rating of a product. The higher the integer, the better the rating.
Your task is to implement a quick sort algorithm to sort the array of product ratings in
descending order, ensuring that the highest-rated products appear first. This will help the
recommendation system to quickly display the best products to the customers.
Given the following array of product ratings: [3, 6, 8, 10, 1, 2, 1], apply your quick sort
algorithm step-by-step and show the intermediate steps of the sorting process.

CONCLUSION:
___________________________________________________________________________
___________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
5 5
Data Analysis &
Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

28 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.09
BINARY SEARCH TREE
OBJECTIVE:
a). Understand concepts and usages of binary search tree (b). Practice PLO CLO LL
the implementation of binary search tree 5 4 C-3
Theory Overview:
Binary Search Trees: Stores keys in the nodes in a way so that searching, insertion and
deletion can be done efficiently. Binary search tree is either empty or each node N of tree
satisfies the following property
• The Key value in the left child is not more than the value of root
• The key value in the right child is more than or identical to the value of root
• All the sub-trees, i.e. left and right sub-trees follow the two rules mention above.

Minimum: The minimum element of a binary search tree is the last node of the left roof
Maximum: The maximum element is the last node of the right roof.

29 | P a g e
Data Structures
Department of Computer Science, LGU

Task 1:
Write a menu driven program of binary search tree that involves following operations:
➢ Inserting and deleting an element
➢ Breadth First Traversal and Depth First Traversal
➢ Finding height of a tree
➢ Maximum and Minimum node

CONCLUSION:
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
5 5
Data Analysis &
Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

30 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.10
AVL Tree
OBJECTIVE:
Understand the concepts if AVL Tree. PLO CLO LL
Implementation of AVL Tree. 5 4 P-3
Theory Overview:
An AVL tree is a self-balancing binary search tree (BST), named after its inventors Adelson-
Velsky and Landis. It maintains balance by ensuring the heights of the left and right subtrees
of any node differ by at most one. This balance is achieved through rotations during insertion
and deletion operations, which guarantees that the tree remains approximately balanced,
providing efficient search, insertion, and deletion operations with a time complexity of O(log
n).
Properties of AVL Trees

1. Binary Search Tree Property:


o For any node NNN, all elements in the left subtree of NNN are less than NNN
and all elements in the right subtree are greater than NNN.
2. Balance Factor:
o The balance factor of a node is defined as the height difference between its left
and right subtrees.
o For every node NNN, the balance factor BF(N)BF(N)BF(N) is calculated as:
BF(N)=height(left subtree)−height(right subtree)BF(N) = \text{height(left
subtree)} - \text{height(right
subtree)}BF(N)=height(left subtree)−height(right subtree)
o The tree is balanced if the balance factor of every node is either -1, 0, or 1.
3. Height:
o The height of an AVL tree with nnn nodes is O(log⁡n)O(\log n)O(logn).

Rotations in AVL Trees

To maintain the balance factor within the permissible range, AVL trees perform rotations
when nodes are inserted or deleted. There are four types of rotations:

1. Right Rotation (Single Rotation):


o Used to balance a left-heavy subtree.
o Applied when a left child's left subtree causes imbalance.
o Procedure:
1. Perform a right rotation on the unbalanced node.

2.Left Rotation (Single Rotation):

o Used to balance a right-heavy subtree.


o Applied when a right child's right subtree causes imbalance.
o Procedure:
1. Perform a left rotation on the unbalanced node.
2. Left-Right Rotation (Double Rotation):
o Used to balance a left-heavy subtree with a right-heavy left child.

31 | P a g e
Data Structures
Department of Computer Science, LGU

oApplied when a left child's right subtree causes imbalance.


oProcedure:
1. Perform a left rotation on the left child.
2. Perform a right rotation on the unbalanced node.
3. Right-Left Rotation (Double Rotation):
o Used to balance a right-heavy subtree with a left-heavy right child.
o Applied when a right child's left subtree causes imbalance.
o Procedure:
1. Perform a right rotation on the right child.
2. Perform a left rotation on the unbalanced node.

AVL Tree Operations

1. Insertion:
o Insert the new node as in a standard BST.
o Update the height of the ancestor nodes.
o Rebalance the tree by performing the necessary rotations if any node becomes
unbalanced.
2. Deletion:
o Delete the node as in a standard BST.
o Update the height of the ancestor nodes.
o Rebalance the tree by performing the necessary rotations if any node becomes
unbalanced.
3. Search:
o Perform the search operation as in a standard BST.
o Time Complexity: O(logn) due to the balanced nature of the AVL tree.

32 | P a g e
Data Structures
Department of Computer Science, LGU

Task 1:

Build an AVL tree with the following values:

15, 20, 24, 10, 13, 7, 30, 36, 25

Task 2:
Write c++ code for insertion and deletion operation in AVL.

CONCLUSION:
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
5 5
Data Analysis &
Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

33 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.11
Heap
OBJECTIVE:
Understand the concepts if Heap Data Structure PLO CLO LL
Implementation of Heap Structure. 5 4 P-3
Theory Overview:
Heap Data Structure

A heap is a specialized tree-based data structure that satisfies the heap property. There are
two types of heaps: max-heaps and min-heaps.

Max-Heap

Property: In a max-heap, for any given node iii, the value of iii is greater than or equal to the
values of its children. The largest element is at the root.

Example:

markdown
Copy code
50
/ \
30 20
/ \ /\
15 10 8 16
Min-Heap

Property: In a min-heap, for any given node iii, the value of iii is less than or equal to the
values of its children. The smallest element is at the root.

Example:

markdown
Copy code
10
/ \
20 15
/ \ /\
30 40 50 100
Properties of Heaps

1. Complete Binary Tree: A heap is a complete binary tree, meaning all levels are fully
filled except possibly the last level, which is filled from left to right.
2. Heap Property: The value of each node is greater than or equal to (max-heap) or less
than or equal to (min-heap) the values of its children.

34 | P a g e
Data Structures
Department of Computer Science, LGU

3. Height: The height of a heap is O(log⁡n)O(\log n)O(logn), where nnn is the number
of nodes.

Operations on Heaps

1. Insertion:
o Add the new element at the end of the heap (last position of the array).
o Heapify up: Compare the added element with its parent; if they are in the
wrong order (violating the heap property), swap them. Repeat until the heap
property is restored.
o Time Complexity: O(log⁡n)O(\log n)O(logn).
2. Deletion (Extract Max/Min):
o Remove the root element (max or min element).
o Replace the root with the last element in the heap.
o Heapify down: Compare the new root with its children; if they are in the
wrong order, swap them with the larger child (for max-heap) or smaller child
(for min-heap). Repeat until the heap property is restored.
o Time Complexity: O(log⁡n)O(\log n)O(logn).
3. Heapify:
o Converts an arbitrary array into a heap.
o Start from the last non-leaf node and move upwards, applying the heapify
down process.
o Time Complexity: O(n)O(n)O(n).
4. Peek:
o Return the root element without removing it.
o Time Complexity: O(1)O(1)O(1).

Applications of Heaps

1. Priority Queues: Heaps are commonly used to implement priority queues, where
elements are dequeued in order of their priority.
2. Heap Sort:
o Build a max-heap from the array.
o Swap the root with the last element and reduce the heap size by one.
o Heapify down the new root.
o Repeat until the heap size is reduced to one.
o Time Complexity: O(nlogn).
3. Graph Algorithms:
o Dijkstra's shortest path algorithm.
o Prim's minimum spanning tree algorithm.

Comparison with Other Data Structures

• Balanced Binary Search Trees (BST): Heaps provide better performance for priority
queue operations (insert and delete) but do not support ordered operations (like in-
order traversal) as efficiently as BSTs.

35 | P a g e
Data Structures
Department of Computer Science, LGU

• Arrays: Heaps allow for efficient insertion and deletion of the highest (or lowest)
priority element, unlike arrays where these operations can be more costly.

36 | P a g e
Data Structures
Department of Computer Science, LGU

Task 1:

Which node would be in position 4 of the corresponding array?


1. Given the node in position 4, how could you use arithmetic to determine:
▪ the position of its left child (if any) in the array
▪ the position of its right child (if any) in the array
▪ the position of its parent in the array
2. If we call the remove() method on this heap:
▪ Which item will be removed?
▪ Which item will be copied into the position of the removed item and then be sifted
down to restore the heap?
▪ What will the tree look like after this call to remove()?
3. What will the heap look like after a second call to remove()? After a third call?
4. After completing the three calls to remove(), we then use the insert() method to add an
item with a key of 21. What will the tree look like after that insertion?

37 | P a g e
Data Structures
Department of Computer Science, LGU

CONCLUSION:
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
5 5
Data Analysis &
Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

38 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.12
Graph
OBJECTIVE:
Understand the concepts if graphs
Implementation of graphs PLO CLO LL
5 4 P-3
Theory Overview
Breadth-First Search (BFS)

Concept: BFS is a graph traversal algorithm that explores the nodes level by level. It starts
from a given source node and explores all its neighbors before moving on to the neighbors'
neighbors.

Steps:

1. Initialize a queue and enqueue the starting node.


2. Mark the starting node as visited.
3. While the queue is not empty:
o Dequeue a node from the queue.
o For each unvisited neighbor of the dequeued node:
▪ Mark the neighbor as visited.
▪ Enqueue the neighbor.

Key Points:

• Queue: Uses a queue to keep track of nodes to be explored.


• Level-wise Traversal: Explores nodes level by level, ensuring that all nodes at the
current depth are processed before moving to the next depth level.
• Time Complexity: O(V+E)O(V + E)O(V+E), where VVV is the number of vertices
and EEE is the number of edges.
• Space Complexity: O(V)O(V)O(V), for storing the queue and the visited list.

Applications:

• Finding the shortest path in unweighted graphs.


• Level-order traversal of a tree.
• Solving problems like finding connected components in a graph.

Advantages:

• Guarantees finding the shortest path in unweighted graphs.


• Simple to implement.

Disadvantages:

• Requires additional memory for the queue and visited list.


• May explore a large number of nodes in graphs with high branching factors.

39 | P a g e
Data Structures
Department of Computer Science, LGU

Depth-First Search (DFS)

Concept: DFS is a graph traversal algorithm that explores as far down a branch as possible
before backtracking. It starts from a given source node and explores each branch to its end
before backtracking to explore other branches.

Steps:

1. Initialize a stack (or use recursion) and push the starting node.
2. Mark the starting node as visited.
3. While the stack is not empty:
o Pop a node from the stack.
o For each unvisited neighbor of the popped node:
▪ Mark the neighbor as visited.
▪ Push the neighbor onto the stack.

Key Points:

• Stack/Recursion: Uses a stack or recursion to keep track of nodes to be explored.


• Depth-wise Traversal: Explores nodes along a branch as deep as possible before
backtracking.
• Time Complexity: O(V+E)O(V + E)O(V+E), where VVV is the number of vertices
and EEE is the number of edges.
• Space Complexity: O(V)O(V)O(V) in the worst case for the stack or recursion call
stack.

Applications:

• Detecting cycles in a graph.


• Topological sorting of a Directed Acyclic Graph (DAG).
• Finding connected components in a graph.
• Solving puzzles and problems like mazes and games where backtracking is required.

Advantages:

• Requires less memory than BFS in sparse graphs.


• Can be more efficient than BFS in deep graphs with fewer branches.

Disadvantages:

• Does not guarantee the shortest path in unweighted graphs.


• May get stuck in deep or infinite loops without proper checks.

40 | P a g e
Data Structures
Department of Computer Science, LGU

Task 1:

41 | P a g e
Data Structures
Department of Computer Science, LGU

CONCLUSION:
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
5 5
Data Analysis &
Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

42 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.13
GRAPH- MST
OBJECTIVE:
Understand the concepts and implementation of MST
Theory Overview PLO CLO LL
Spanning Tree: A spanning tree of a graph is an undirected tree 5 4 P-3
consisting of only those edges necessary to connect all the nodes in the original graph.
Minimum Spanning Tree (MST):A minimum spanning tree is a subgraph of an undirected
weighted graph G, such that
• it is a tree (i.e., it is acyclic)
• it covers all the vertices V – contains |V| - 1 edges
• the total cost associated with tree edges is the minimum among all possible spanning trees
Kruskal’sAlgorithm:Kruskal's algorithm is an algorithm in graph theory that finds a
minimum spanning tree for a connected weighted graph. This means it finds a subset of the
edges that forms a tree that includes every vertex, where the total weight of all the edges in
the tree is minimized.At the termination of the algorithm, the forest has only one component
and forms a minimum spanning tree of the graph.
Algorithm:
• create a forest F (a set of trees), where each vertex in the graph is a separate tree as well
• create a set S containing all the edges in the graph
• while S is nonempty – remove an edge with minimum weight from S – if that edge connects
two different trees, then add it to the forest, combining two trees into a single tree – otherwise
discard that edge
• In the subsequent example, a green edge means it has been included into the forest of trees
that will ultimately form a single, minimum spanning tree.

43 | P a g e
Data Structures
Department of Computer Science, LGU

Task 1:
Write a program, which reads an adjacency matrix representation of a graph and applies
Kruskal’s algorithm to find minimum spanning tree of the input graph.

CONCLUSION:
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
_____________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
5 5
Data Analysis &
Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

44 | P a g e
Data Structures
Department of Computer Science, LGU

PRACTICAL NO.14
DIJKSTRA ALGO
OBJECTIVE:
Find shortest path in Graph using Dijkstra Algo.
Theory Overview PLO CLO LL
Dijkstra Algorithm - Shortest Path Calculation: This algorithm is 4 3 3
used to find the shortest path between nodes. The shortest path
may be computed based on number of hops, the distance, bandwidth available, queue lengths
etc. It is widely used in Dynamic routing algorithm.

Dijkstra Algorithm
1. Assign to every node a tentative distance value: set it to zero for our initial node and to
infinity for all other nodes.
2. Mark all nodes unvisited. Set the initial node as current. Create a set of the unvisited nodes
called the unvisited set consisting of all the nodes except the initial node.
3. For the current node, consider all of its unvisited neighbours and calculate their tentative
distances.
4. When we are done considering all of the neighbours of the current node, mark the current
node as visited and remove it from the unvisited set. A visited node will never be checked
again; its distance recorded now is final and minimal.
5. If the destination node has been marked visited (when planning a route between two
specific nodes) or if the smallest tentative distance among the nodes in the unvisited set is
infinity (when planning a complete traversal), then stop. The algorithm has finished.
6. Set the unvisited node marked with the smallest tentative distance as the next "current
node" and go back to step 3.

45 | P a g e
Data Structures
Department of Computer Science, LGU

Task 1:
Consider the following graph and calculate the shortest path using Dijkstra Algorithm from
V0 to V3. Show all the steps involved in the calculations.

CONCLUSION:
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
_____________________

RUBRICS:

Performance Lab Report

Description Total Marks Description Total Marks


Marks Obtained Marks Obtained
Ability to 5 5
Conduct Structure
practical
5 5
Data Analysis &
Efficiency
Interpretation
Total Marks obtained Total Marks Obtained

46 | P a g e

You might also like