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

Assignment DSA

Pearson BTEC

Uploaded by

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

Assignment DSA

Pearson BTEC

Uploaded by

Irunika Sasanthi
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 38

Higher National Diploma in Computing

Course Title Pearson BTEC Level 5 Higher National Diploma in Computing (SE)

Unit Number and Title: Unit 19: Data Structures & Algorithms

Assignment Title Assignment 1

Name of the Learner Thanthirige Dona Sasanthi Irunika


Centre Ref. No of The PSM-7151 Pearson Regd. No. BTSE0322010343
Learner
Assignment Number 1 Batch No & Semester Batch 3 – Semester 4

Issue Date Submission Date 17/03/2024

Filled by Lecturer Date Received 1st Filled by Lecturer


Re-submission Date
submission
Unit Assessor: Mr.Navoda Kotugoda Academic Year

Assessor Summative Feedback

Assessor Feedback:

*Please note that constructive and useful feedback should allow students to understand:

a) Strengths of performance
b) Limitations of performance
c) Transferable skills and competencies developed
d) Any improvements needed in future assessments

Filled by Lecturer

Grade: Filled by Assessor Signature: Filled by Lecturer Date: Filled by Lecturer


Lecturer
Resubmission Feedback - Formative

Grade: Assessor Signature: Date

1
Internal Verifier’s Comments
Filled by IV

Signature of the IV Filled by IV Date Filled by IV


Student Agreement:
Student Signature
I understand the feedback given to me and agree to carry out the actions in
future works as required and indicated. Date

Please note that grade decisions are provisional. They are only confirmed once internal and external
moderation has taken place and grades decisions have been agreed at the assessment board.

STUDENT ASSESSMENT SUBMISSION AND DECLARATION

Student name: Assessor name:


Thanthirige Dona Sasanthi Irunika Mr.Navoda Kotugoda
Issue date: Submission date: Submitted on:
17/03/2024 Filled by Lecturer
Programme:
Pearson BTEC Level 5 Higher National Diploma in Computing (SE)
Unit:
Unit 19: Data Structures & Algorithms
Assignment number and title:
Assignment 1 – Assignment 1

PLAGIARISM
Plagiarism is a particular form of cheating. Plagiarism must be avoided at all costs and students who
break the rules, however innocently, may be penalized. It is your responsibility to ensure that you
understand correct referencing practices. As a university level student, you are expected to use
appropriate references throughout and keep carefully detailed notes of all your sources of materials for
material you have used in your work, including any material downloaded from the Internet. Please consult
the relevant unit lecturer or your course tutor if you need any further advice.

2
Student Declaration

Student declaration

I certify that the assignment submission is entirely my own work and I fully understand the
consequences of plagiarism. I understand that making a false declaration is a form of malpractice.

Student signature: T D S Irunika Date: 17/03/2023

SUBMISSION FORMAT

Assignment Learning Outcome Task Submission Format Page Number

P1, P2, P3, P4, P5, 01 Report


P6,P7,P8M1, M2,
M3, M4,M5,D1, 02 Report
D2
1 03 Report

04 Report

05 Report

ASSESSMENT REVIEW PLAN

Grading Evidence Formative Comments Date


Assignment
Criteria

01 P1

3
P2

P3

P4

P5

P6

P7

P8

M1

M2

M3

M4

D1

D2

ASSESSMENT TRACKING
ASSESSMENT RECORD AND FEEDBACK SHEET

Thanthirige
BTEC HN in Assessment
Programme: Student Name: Dona Sasanthi
Computing (SE) Date:
Irunika

Unit 19: Data


Unit No. &
Structures & Year 2023 Unit Grade:
Title:
Algorithms

Mr.Navoda Unit Completion Filled by IV


Assessor Name: Filled by IV
Kotugoda Date: Lecturer Signature:

Assignmen Learning Objectives Criteria Date Hand In Sammativ Resubmissi


t No and Targeted Issued Date e on Date*
Title

4
Feedback

P1, P2, P3,


LO1
P4, P5,
LO2 P6,P7,P8,
01 M1, M2,
LO3
M3, M4,
LO4
D1, D2

* Resubmissions must be approved by the Assessment Board

SUMMATIVE FEEDBACK

Assignment Grading Date Assessor


Comments
No. Criteria Achieved Signature

P1

P2

Assignment 1 P3

P4

P5

5
P6

P7

P8

M1

M2

M3

M4

D1

D2

6
Higher National Diploma in
Computing
Unit 25: Machine Learning

Assessment Brief

Student Thanthirige Dona Sasanthi Irunika / BTSE0322010343


Name/ID
Number
Unit Number and Unit 19: Data Structures & Algorithms
Title
Academic Year 2023

Unit Tutor Mr.Navoda Kotugoda

Assignment Title Assignment 01

Issue Date

Submission Date 17/03/2024

IV Name & Date

7
Table of Contents
LO1 Examine abstract data types, concrete data structures and algorithms....................................................10
What are data structures?.............................................................................................................................10
Usage of the Data structures........................................................................................................................10
Data structure types......................................................................................................................................11
Linear data structures...................................................................................................................................11
Non-linear data structures............................................................................................................................13
Linear......................................................................................................................................................14
Non-Linear..............................................................................................................................................14
Data elements are arranged in a linear order............................................................................................14
Data elements are attached in hierarchically manner...............................................................................14
Single level is involved............................................................................................................................14
Multiple levels are involved.....................................................................................................................14
Implementation is easy when it compares to Non-linear.........................................................................14
Implementation is complex, when it compares to Linear........................................................................14
Only one run is possible for data elements..............................................................................................14
Data items cannot be accessed in a single run.........................................................................................14
The efficient use of memory is lacking....................................................................................................14
Effective use is made of memory.............................................................................................................14
Abstract data types.......................................................................................................................................14
Abstract data type model..............................................................................................................................15
List ADT..................................................................................................................................................15
Stack ADT................................................................................................................................................16
Queue ADT..............................................................................................................................................16
What is Algorithm?......................................................................................................................................17
Types of Algorithm..................................................................................................................................17
Algorithms................................................................................................................................................18
Formal Notation of a Singly Linked List Data Structure.........................................................................18
Activity 2......................................................................................................................................................19
Activity 2.2..............................................................................................................................................24
Activity 2.3..............................................................................................................................................26
Activity 2.4 Advantages of encapsulation and information hiding in a SinglyLinkedList structure.......28
Activity 2.5...............................................................................................................................................28
Activity 3.1 Assessing the complexity of an algorithm using asymptotic analysis:....................................29
Activity 3.2 Finding the efficiency of the viewCallLog method in the SinglyLinkedList class.................29
Activity 3.3 Critically evaluating the complexity of the viewCallLog method in the MessageStack class 30
Activity 3.4 Time-space trade-off in algorithms..........................................................................................30
8
Activity 4......................................................................................................................................................31
Activity 5......................................................................................................................................................33
Activity 6......................................................................................................................................................34
Dijkstra's Method:....................................................................................................................................34
Bellman-Ford Algorithm:.........................................................................................................................35
Activity 7......................................................................................................................................................36
References........................................................................................................................................................38

9
LO1 Examine abstract data types, concrete data structures and algorithms
What are data structures?
A data structure is a type of specialized format used to process, retrieve, and organize data. Numerous
fundamental and sophisticated data structures are all intended to organize data for a particular use. Users
may easily access and manipulate the necessary data in the right manner with the help of data structures. The
main benefit of data structures is that they help both humans and robots understand the way information is
organized.

Data structures are chosen or created in computer science and computer programming to store information
for usage with different algorithms. The design of the structure and the algorithm's fundamental operations
are sometimes closely related. The values of the data, the connections between the data, and, occasionally,
functions that can be used with the data are all included in each data structure.

An OOP language, for example, binds the data structure and its methods together as part of the class
definition. Functions that are defined to operate with a data structure may exist in non-OOP languages, but
they are not considered to be a part of data structures.

Usage of the Data structures


To implement the physical representations of abstract data types, data structures are typically utilized. The
design of effective software requires the use of data structures. Furthermore, they are essential to the
creation of algorithms and how computer programs employ such algorithms. (David Loshin, 2021)

Here are some instances where data structures are put to use:

1. Storing data: In a database management system, for example, data structures are used to indicate the
collection of attributes and related structures that are used to store records. This allows for efficient
data persistence.
2. Overseeing assets and offerings Process scheduling queues, file directory management, memory
allocation, and file structure trees are examples of data structures that are used to allow core
operating system (OS) resources and functions.
3. Data exchange: Data structures specify how information shared by apps, such as TCP/IP packets, is
organized.
4. Sorting and ordering: Binary search trees, sometimes referred to as ordered or sorted binary trees,
are data structures that offer effective ways to arrange items, including character strings that are
utilized as tags. Programmers can handle objects arranged based on a specified priority by using data
structures like priority queues.
5. Indexing: To index objects, such as those kept in a database, even more complex data structures like
B-trees are employed.
10
6. Searching: Indexes built with hash tables, binary search trees, or B-trees expedite the process of
locating a particular object that is sought after.

Data structure types


Basically, data structures are divided in to two categories:
1. Linear data structures
2. Non-linear data structures

Linear data structures


The components of linear data structures are organized sequentially, one after the other. The elements are
simple to execute since they are placed in a specific order.
However, due to operational complexity, linear data structures may not be the ideal option when program
complexity rises.

 Array
An array is a group of items kept close at different memory locations. The same type of items is stored
together so that an index may quickly determine or retrieve each element's place. Arrays' lengths can be
either fixed or variable.

Figure 1 - Array
 Stack
Stores elements according to the Last-In-First-Out (LIFO) principle, used for program state tracking and
LIFO-based problem-solving.

11
Figure 2 - Stack
 Queues
Operate on the First-In-First-Out (FIFO) principle, managing resources, handling interruptions, and
scheduling tasks.

Figure 3 - Queue

 Linked Lists
Collections of nodes, each containing data and a reference to the next node, suited for variable-sized data
sets.

Figure 4 – Linked List

12
Non-linear data structures
Non-linear data structures do not have items in a specific sequence, in contrast to linear data structures.
As an alternative, they are arranged hierarchically, with each element being connected to one or more
others.
Graph and tree-based data structures are two more categories of non-linear data structures. (Unknown,
n.d.)

 Tree
Hierarchical structures of nodes connected by edges are used for representing hierarchical data.

Figure 5 – Tree

 Graph
Collections of vertices connected by edges, are essential for modeling complex relationships.

13
Figure 6 – Graph

Difference between linear and non-linear Data Structures

Linear Non-Linear
Data elements are arranged in a linear Data elements are attached in hierarchically
order. manner.
Single level is involved. Multiple levels are involved.
Implementation is easy when it Implementation is complex, when it
compares to Non-linear compares to Linear.
Only one run is possible for data Data items cannot be accessed in a single
elements. run.
The efficient use of memory is Effective use is made of memory.
lacking.
Table 1 - Difference between linear and non-linear Data Structures
Abstract data types
A programming notion known as an Abstract Data Type (ADT) describes a high-level representation of a
data structure without going into specifics about how it will be implemented. Put differently, it is a data
structure design blueprint that outlines the structure's behavior and interface but leaves out the details of
how it should be implemented.
You may think of an ADT in the data structure as a collection of operations that can be applied to a given
set of values. These operations are used to alter the data in a way that best fits the requirements of the
application and determine the behavior of the data structure.
ADTs are frequently used to give access to and manipulation of data a straightforward and user-friendly
interface while abstracting away the intricacy of a data structure. This facilitates programmers' ability to
use data structures correctly and to reason about them. (Kochar, 2023)

14
Abstract data type model

Figure 7 – Abstract data type

List ADT
For storing data in a non-continuous structure, lists are linear data structures. The items on the list are called
"nodes," which are little data storage units. The addresses of other blocks are contained in each of these
nodes since they are connected. Consequently, these linkages establish a connection between each node.
(Kochar, 2023)

Figure 8 – List ADT


The following is a list of some of the most crucial operations that List ADT defines.

a) front (): gives back the value of the node that is at the head of the list.
b) back (): gives back the value of the node that is at the end of the list.
c) push_front(int val): maintains this pointer at the front of the linked list by creating a pointer with
value = val.
d) push_back(int val): maintains a pointer to the rear of the linked list and generates a pointer with
value= val.
e) pop_front(): eliminates the node at the front of the list.
f) pop_back(): eliminates the list's final node.

15
g) empty (): If the list is empty, the function returns true; otherwise, it returns false.
h) size (): yields the total number of nodes in the list.

Stack ADT
In a stack, data can only be retrieved from the top. It is a linear data structure. It only performs two
operations: pop, which removes data from the stack, and push, which adds data to the top of the stack. (Used
to clear data off of the top of the stack) (Kochar, 2023).

Figure 9 – Stack ADT


The following is a list of some of the most crucial operations that are defined in Stack ADT.

a) top(): gives back the value of the node at the top of the stack.
b) push(int val): constructs a node and places it at the top of the stack with value = val.
c) pop(): eliminates the node at the top of the stack.
d) empty(): If the stack is empty, the function returns true; otherwise, it returns false.
e) size(): yields the total number of nodes in the stack.

Queue ADT
Data can be accessed from both ends of a queue, which is a linear data structure. The push and pop
operations are the two primary operations in a queue; the former is used to add data to the back of the
queue while the latter is used to remove data from the front. Data can be accessed from both ends of a
queue, which is a linear data structure. The push and pop operations are the two primary operations in a

16
queue; the former is used to add data to the back of the queue while the latter is used to remove data from
the front.
Figure 10 – Queue ADT
Below is a list of some of the most crucial operations that Queue ADT defines.
a) front(): gives back the value of the queue's leading node.
b) back(): gives back the value of the node that is at the end of the queue.
c) push(int val): establishes a node at the front of the queue with value = val.
d) pop(): eliminates the node from the back of the queue.
e) empty(): If the queue is empty, the function returns true; otherwise, it returns false.
f) size(): gives back the total number of nodes in the queue.

What is Algorithm?
Algorithms are well-defined sets of instructions that tackle specific problems or execute tasks. They are the
foundational components of computer programs and are essential for addressing complex computational
challenges. Algorithms come in various forms, including sorting, searching, graph, optimization, and many
others. Algorithms can be represented in different ways, such as programming code, flowcharts, or pseudo
code. They are characterized by factors like accuracy, running time, and memory utilization, which impact
their efficiency and effectiveness. (Muskan, n.d.)

Types of Algorithm
a) Brute Force Algorithm - This is the most fundamental and straightforward. A Brute Force Algorithm
is the simplest solution to a problem—that is, the first solution that occurs to us when we perceive the
problem. In technical terms, it's equivalent to trying every possible solution repeatedly to that issue.
(Muskan, n.d.)
b) Recursive Algorithm - The foundation of this algorithm is recursion. Recursion is a technique for
solving problems where a problem is divided into smaller problems of the same kind and then called
again and again until the problem is resolved with the aid of a base condition.
Factorial of a Number, Fibonacci Series, Tower of Hanoi, DFS for Graph, and more basic problems
are handled by recursive algorithms. (Muskan, n.d.)
c) Divide Algorithm - Dividing the problem into two portions and solving each one separately is the
premise behind Divide algorithms. To arrive at the final solution to the problem, the second section
involves solving the smaller problem on its own and adding the total result.
Binary search, merge sort, quick sort, Strassen's matrix multiplication, and other issues are among the
typical problems that are resolved using divide algorithms. (Muskan, n.d.)

17
d) Dynamic Algorithm - The memoization approach is another name for this algorithm, which stores the
result of a previous calculation to save repeating the calculation. Divide the large problem using
dynamic programming into smaller, overlapping subproblems, then store the solution for later use.
Dynamic programming algorithms such as Floyd Warshall, Knapsack Problem, and Weighted Job
Scheduling can be used to handle the following issues. (Muskan, n.d.)
e) Greedy Algorithm - The Greedy Algorithm builds the solution piece by piece. The next section is
selected based on the fact that it provides an instant benefit. It never takes past decisions into account.
Dijkstra Shortest Path Algorithm, Prim's Algorithm, Kruskal's Algorithm, Huffman Coding, and other
popular issues are among those that can be resolved with the Greedy Algorithm.
f) Randomize Algorithm - For the randomized algorithm, a random number is employed. Setting an
expectation for the result is helpful. The choice of a random number to provide an instant advantage
Quicksort is one typical issue that the Randomized Algorithm can handle. When using Quicksort, the
pivot is chosen at random.

Algorithms
1. Sort
a) Insertion sort: Repeatedly inserts elements into a sorted area of the array; effective for small
datasets.
b) Quick Sort: Partitions the array recursively using a pivot element, utilizing the divide and conquer
strategy.
c) Merge Sort: Sorts the array in half, merges the two pieces after sorting each one.
d) Heap Sort: creates a heap out of the array and pulls out the maximum element many times.
e) Bucket Sort: Concatenates components after distributing them into buckets and sorting each
bucket.
f) Selection Sort: Chooses the smallest element repeatedly and replaces it with the element that was
not sorted initially.
2. Search
a) Linear Search: Scans each element one after the other until the target is located.
b) Binary Search: Divide the search interval in half repeatedly to efficiently search a sorted array.
c) Binary Search Tree (BST) Search: Makes effective use of a BST's features to find an element.
d) Recursive Binary Tree Traversals: Recursively navigates binary trees in pre-order, in-order, and
post-order variations.
3. Path Findings
a) Finding Paths in Graph: Uses strategies to locate pathways between nodes in a network, such as
Depth-First Search (DFS) and Breadth-First Search (BFS).

18
b) Travelling Salesman Problem: Uses heuristics like the nearest neighbor approach or optimization
techniques like dynamic programming to discover the shortest route that visits each city precisely
once and returns to the starting point.

Formal Notation of a Singly Linked List Data Structure


A Singly Linked List is a basic data structure made up of nodes, each of which has a reference to the node
after it in the sequence and data. The components and structure of a singly linked list are formalized by the
following notation:

SinglyLinkedList = (Node, firstnode, lastnode)

This notation contains:

 SinglyLinkedList: This data structure represents all of the Singly Linked List entries. It makes the
list easier to access and serves as a container for the nodes.
 Node: Indicates each of the Singly Linked List's constituent parts. The record structure consists of
two necessary fields:
 Data: Stores the real information or value related to the node.
 Next: Has a pointer or reference to the node that comes after it in the sequence. Traversing the list is
made possible by this reference, which also creates the connection between the nodes.
 firstnode: Indicates a pointer to the linked list's initial node. It acts as the point of entry for getting to
and looking through the list.
 lastnode: A pointer to the linked list's last node is indicated by this. This pointer aids in locating the
list's termination point and effectively attaching new nodes to the end of the list.

Activity 2

class ListNode {

String phoneNumber;

ListNode next;

public ListNode(String phoneNumber) {

this.phoneNumber = phoneNumber;

19
this.next = null;

public class SinglyLinkedList {

private ListNode head;

2.1. a. Singly LinkedList constructor with no parameters

public SinglyLinkedList() {

this.head = null;

2.1. b Singly LinkedList constructor with one parameter which contains a list node

public SinglyLinkedList(ListNode node) {

this.head = node;

2.1. c isEmpty function which indicates whether the list is empty or not by returning true or false

public boolean isEmpty() {

return head == null;

2.1. d firstElement function which returns the telephone number in the first node if exists or throws
an exception if it does not contain any nodes

public String firstElement() throws Exception {

if (isEmpty()) {

20
throw new Exception("List is empty");

return head.phoneNumber;

2.1. e lastElement function which returns the telephone number in the last node if exists or throws
an exception if it does not contain any nodes

public String lastElement() throws Exception {

if (isEmpty()) {

throw new Exception("List is empty");

ListNode current = head;

while (current.next != null) {

current = current.next;

return current.phoneNumber;

2.1. f insertFromTail function which adds a new telephone number to the tail of the call log

public void insertFromTail(String phoneNumber) {

ListNode newNode = new ListNode(phoneNumber);

if (isEmpty()) {

head = newNode;

} else {

ListNode current = head;

while (current.next != null) {

21
current = current.next;

current.next = newNode;

2.1. g insertFromFront function which adds a new telephone number to the front of the call log

public void insertFromFront(String phoneNumber) {

ListNode newNode = new ListNode(phoneNumber);

if (!isEmpty()) {

newNode.next = head;

head = newNode;

2.1. h deleteFromTail function which will delete the last telephone number in the list. If it does not
exist, will throw an exception

public void deleteFromTail() throws Exception {

if (isEmpty()) {

throw new Exception("List is empty");

if (head.next == null) {

head = null;

return;

ListNode prev = null;

22
ListNode current = head;

while (current.next != null) {

prev = current;

current = current.next;

prev.next = null;

2.1. I deleteFromFront function which will delete the first telephone number in the list. If it does not
exist, will throw an exception

public void deleteFromFront() throws Exception {

if (isEmpty()) {

throw new Exception("List is empty");

head = head.next;

2.1. j viewCallLog method will display all the elements in the list from first element to last element.
Further it will result an error message if there are no telephone numbers

public void viewCallLog() {

if (isEmpty()) {

System.out.println("Call log is empty");

return;

ListNode current = head;

System.out.println("Call Log:");

23
while (current != null) {

System.out.println(current.phoneNumber);

current = current.next;

public static void main(String[] args) {

SinglyLinkedList callLog = new SinglyLinkedList();

Inserting elements to the call log

callLog.insertFromTail("1234567890");

callLog.insertFromTail("0987654321");

callLog.insertFromFront("9999999999");

Viewing call log

callLog.viewCallLog();

try {

// Deleting elements from the call log

callLog.deleteFromFront();

callLog.deleteFromTail();

Viewing call log after deletion

callLog.viewCallLog();

Trying to delete from an empty list

24
callLog.deleteFromTail();

} catch (Exception e) {

System.out.println(e.getMessage());

Activity 2.2
public class MessagingStack {

private SinglyLinkedList stack;

public MessagingStack() {

this.stack = new SinglyLinkedList();

public void push(String message) {

stack.insertFromFront(message);

public String pop() throws Exception {

if (isEmpty()) {

throw new Exception("Stack is empty");

String message = stack.firstElement();

stack.deleteFromFront();

return message;

25
public String peek() throws Exception {

if (isEmpty()) {

throw new Exception("Stack is empty");

return stack.firstElement();

public boolean isEmpty() {

return stack.isEmpty();

public void viewStack() {

stack.viewCallLog();

Activity 2.3
public class Main {

public static void main(String[] args) {

// Creating a MessagingStack object

MessagingStack messageStack = new MessagingStack();

// Inserting messages into the stack

messageStack.push("Message 1");

messageStack.push("Message 2");

messageStack.push("Message 3");

26
messageStack.push("Message 4");

messageStack.push("Message 5");

// Displaying the stack

System.out.println("Initial stack:");

messageStack.viewStack();

try {

// Popping messages from the stack

System.out.println("\nPopped messages:");

while (!messageStack.isEmpty()) {

System.out.println(messageStack.pop());

} catch (Exception e) {

System.out.println(e.getMessage());

Output:

Initial stack:

Call Log:

Message 5

Message 4

Message 3

Message 2

Message 1

27
Popped messages:

Message 5

Message 4

Message 3

Message 2

Message 1

Activity 2.4 Advantages of encapsulation and information hiding in a SinglyLinkedList structure


1. Integrity of data: Encapsulation helps to protect data integrity by limiting access to the
SinglyLinkedList class's internal state. Can stop external code from changing the state of the list in an
unexpected or inconsistent way by masking the implementation details of the class.
2. Interface simplification: The SinglyLinkedList class's interface can be made straightforward and
consistent by using encapsulation. Can make the class easier to use and comprehend for other
developers by providing a clear and succinct set of methods for dealing with the list while concealing
the implementation specifics.
3. Improved performance: The SinglyLinkedList class's performance can also be enhanced via
encapsulation and information hiding. Can optimize the internal operations of the class without
affecting the code that utilizes it by hiding the implementation details. This may result in code that is
quicker and more effective.
4. Loose coupling: The SinglyLinkedList class and other classes have less coupling when encapsulation
is used. Can modify the internal operations of the class without impacting the code that utilizes it by
concealing the implementation details. This facilitates the class's ongoing upkeep and evolution.
5. Simplified interface: You can design a straightforward and uniform interface for the
SinglyLinkedList class by using encapsulation. It is easier for other developers to use and comprehend
the class when you hide the implementation details and give a succinct and straightforward set of
methods for dealing with the list.

Activity 2.5
I concur that imperative Abstract Data Types (ADTs) serve as the foundation for object-oriented
programming.

An instance of a class that has data and activity is referred to as an object in object-oriented programming.
A class serves as a template for building objects, outlining the properties and set of data that each object in

28
the class will possess. An ADT is a data type mathematical model that specifies the operations that can be
carried out on the data type.

ADTs specified in terms of imperative statements—statements that specify how to carry out an operation
—are known as imperative ADTs. Declarative ADTs, on the other hand, are ADTs that are described in
terms of declarative statements, which are statements that specify what happens after an operation.

The foundation of object-oriented programming is provided by imperative ADTs, which allow you to
define a class's behavior in terms of imperative statements. Stated otherwise, they offer a means of
specifying a class's methods in terms of their appropriate implementation. This is a crucial component of
object-oriented programming because it makes it possible to specify a class's behavior in a style that is
simple to comprehend and apply.

Take the SinglyLinkedList class that we previously defined, for instance. Because it explains how to add a
new node at the end of the list, the class's insertFromTail method is an imperative method. The new node is
appended to the end of the list by the procedure, which loops through the list until it reaches the last node.
Given that it specifies how to carry out the operation, this is an illustration of an imperative method.

Activity 3.1 Assessing the complexity of an algorithm using asymptotic analysis:


Asymptotic analysis is a technique used to evaluate an algorithm's complexity by looking at how well it
performs in relation to the size of the input. Finding out how an algorithm's running time or space needs rise
as the size of the input increases is the aim of asymptotic analysis.

Asymptotic analysis frequently employs a number of notations, such as these:

a) Big O notation: This notation is used to express an algorithm's upper bound for space or running time
needs. It stands for the algorithm's worst-case situation.
b) Omega notation: An algorithm's bottom bound for running time or space needs is expressed using this
notation. For the algorithm, it embodies the optimal situation.
c) Theta notation: This notation is used to specify the precise bound of an algorithm's space or running
time needs. It stands for the algorithm's worst-case scenario

Activity 3.2 Finding the efficiency of the viewCallLog method in the SinglyLinkedList class
The viewCallLog method in the SinglyLinkedList class can be found efficient in two ways:

a) Counting the operations: Counting the operations that the viewCallLog method completes as a
function of list size is one technique to determine the method's efficiency. In this instance, the phone
number of each node is printed by the viewCallLog method iterating over the collection. As a result,
the quantity of operations and the list size are equal. This indicates that the viewCallLog method's
running time is O(n), where n is the list's size.

29
b) Using a profiler: Using a profiler is an additional method to determine the viewCallLog function's
performance. A profiler is a tool that gathers information about a program's execution to gauge its
performance. The viewCallLog method's running time can be measured as a function of list size
using a profiler. This will enable you to observe how the method's running time varies with list size.

Here is an example of how to measure the Java viewCallLog method's running time using a profiler:

i. Run the SinglyLinkedList class using the viewCallLog function after compiling it.
ii. Start profiling the program by using the profiler.
iii. Use a list of a specified size when calling the viewCallLog function.
iv. Utilize the profiler to determine how long the viewCallLog method takes to execute.
v. With lists of various sizes, repeat steps 3 and 4 again.
vi. Determine the execution time of the viewCallLog method as a function of the list size by
analyzing the data that the profiler acquired.
vii. A profiler can help to obtain a more precise and comprehensive image of the viewCallLog
method's effectiveness. This can aid in method optimization and performance enhancement.

Activity 3.3 Critically evaluating the complexity of the viewCallLog method in the MessageStack
class
A SinglyLinkedList class is used in the implementation of the viewCallLog method in the MessageStack
class. The SinglyLinkedList class's viewCallLog method has an O(n) execution time, where n is the list size,
as previously mentioned. This is a result of the approach printing each node's phone number as iteratively
going through the list.

The viewCallLog method in the MessageStack class is implemented as follows:

public void viewCallLog() {

stack.viewCallLog();

That indicates that the viewCallLog method in the SinglyLinkedList class and the viewCallLog method in
the MessageStack class have the same running times. Consequently, the MessageStack class's viewCallLog
method has an O(n) execution time, where n is the stack's size.

Activity 3.4 Time-space trade-off in algorithms


The link between an algorithm's running time and its space needs is known as the "time-space trade-off" in
algorithms. An algorithm's space requirements and running time are typically trade-offs; that is, decreasing
an algorithm's running time typically results in an increase in its space requirements, and vice versa.
30
Take into consideration, for instance, the following procedure for determining an array's maximum element:

public static int findMax(int[] arr) {

int max = arr[0];

for (int i = 1; i < arr.length; i++) {

if (arr[i] > max) {

max = arr[i];

return max;

The running time of this algorithm is O(n), where n is the array's size. But because it only has to keep the
maximum element at that moment and the index of the element after it to compare it with, it only needs a
fixed amount of space.

Activity 4
A priority queue data structure can be used to create the feature that allows messages to be forwarded to
specific recipients in a First Selected First Forward fashion. An element with the highest (or lowest) priority
can be retrieved from a group of elements stored in a priority queue.

This is an illustration of how to set up a priority queue in Java for message forwarding.

1. Make a Message class with a priority property to represent a message. An integer that indicates the
message's priority may be entered in the priority field. A communication with a higher priority could,
for instance, be represented by a lower priority number.

public class Message {


private int priority;
private String message;

public Message(int priority, String message) {


this.priority = priority;
this.message = message;
}

31
public int getPriority() {
return priority;
}

public String getMessage() {


return message;
}
}
2. To depict a message priority queue, create a MessageQueue class. A PriorityQueue object can be used
by the MessageQueue class to hold messages. Java comes with a built-in class called PriorityQueue that
implements a priority queue data structure.

import java.util.PriorityQueue;

public class MessageQueue {


private PriorityQueue<Message> queue;

public MessageQueue() {
queue = new PriorityQueue<>(new MessageComparator());
}

public void enqueue(Message message) {


queue.add(message);
}

public Message dequeue() {


return queue.poll();
}

private class MessageComparator implements Comparator<Message> {


public int compare(Message m1, Message m2) {
return Integer.compare(m1.getPriority(), m2.getPriority());
}
}
}

32
3. To forward messages in a First Selected First Forward fashion to the designated recipients, using the
MessageQueue class.

public class MessageForwarder {


private MessageQueue queue;

public MessageForwarder() {
queue = new MessageQueue();
}

public void forwardMessage(Message message, List<Recipient> recipients) {


for (Recipient recipient : recipients) {
queue.enqueue(new Message(recipient.getPriority(), message.getMessage()));
}

while (!queue.isEmpty()) {
Message message = queue.dequeue();
sendMessage(message, message.getRecipient());
}
}

private void sendMessage(Message message, Recipient recipient) {


// Code to send the message to the recipient
}
}
In this instance, the messages that need to be sent are stored in a MessageQueue object by the
MessageForwarder class. The forwardMessage method enqueues the message for each recipient in the
priority queue after receiving a message and a list of recipients as input. The message with the highest
priority—that is, the one with the lowest priority number—can be retrieved from the queue using the
dequeue method of the MessageQueue class. The message is subsequently sent to the receiver by
invoking the sendMessage method.

Because the messages are placed in a priority queue and the message with the greatest priority is always
retrieved first, this approach guarantees that the messages are forwarded to the recipients in a First
Selected First Forward manner.

33
Activity 5
The two sorting algorithms below can be examined in order to assess how well they function while
showing the contact list in a firmware:
a) Bubble Sort: Bubble sort is a basic sorting algorithm that goes through the list several times,
compares neighboring elements, and switches elements if they are out of order. Until the list is sorted,
the algorithm keeps going through this procedure.

In the worst scenario, the bubble sort running time is O(n^2), where n is the array's size. This is due to the
possibility that the algorithm will need to swap and compare each member in the array up to n times.

b) Quick Sort: This divide-and-conquer sorting technique divides the array into two sub-arrays using a
pivot element. After that, the sub-arrays are sorted recursively.

In the average scenario, quick sort takes O(n log n) time to complete, where n is the array's size. This is
due to the fact that the sub-arrays are sorted recursively and the array is split into two halves at each step
of the method.

Asymptotic analysis can be used to compare the performance of these two algorithms. Asymptotic
analysis is a technique used to evaluate an algorithm's complexity by looking at how well it performs in
relation to the size of the input. Finding out how an algorithm's running time or space needs rise as the
size of the input increases is the aim of asymptotic analysis.

The number of contacts in the contact list, which is a fixed size array, equals the size of the input in this
instance. As a result, the number of elements in the array will determine the sorting algorithm's running
time rather than the size of the input.

The asymptotic analysis indicates that bubble sort performs worse than quick sort when it comes to
sorting the contact list. This is due to the fact that bubble sort has an O(n^2) running time in the worst
scenario, but rapid sort has an O (n log n) running time in the average scenario. This means that,
especially for large lists, rapid sort will sort the contact list more quickly than bubble sort.

Activity 6
Dijkstra's Algorithm and Bellman-Ford Algorithm can be used to find the shortest path to each of the other
sites, assuming the user is at point S.

Dijkstra's Method:
In a weighted network, the greedy Dijkstra's Algorithm determines the shortest path between each source
node and every other node. To choose the node that is closest to the source node, a priority queue is used.
The distance to the source node is set to 0 and the distance to all other nodes is set to infinity at the
beginning of the method. After that, until every node has been visited, it keeps choosing the one with the
shortest distance, updates the distances to its neighbors, and marks the node as visited.

34
The following are the shortest paths, determined using Dijkstra's Algorithm, from location S to every other
location:

S to A: 0 (S is the source node)

S to B: 5 (S to A to B)

S to C: 8 (S to A to B to C)

S to D: 1 (S to D)

S to E: 2 (S to A to E)

S to F: 6 (S to A to B to F)

Bellman-Ford Algorithm:
A weighted graph's shortest path from a source node to every other node is found using the Bellman-Ford
Algorithm, a dynamic programming method. Till there are no more gains possible, it repeatedly relaxes the
edges. The distances between the source node and all other nodes are initially set to 0 and infinity,
respectively, via the procedure. The edges are then continually relaxed, which updates the node's distance if
a shorter path via a nearby node is discovered. To make sure all potential routes have been investigated, the
algorithm iterates n times, where n is the number of nodes.

The shortest routes from location S to every other location are the same as those discovered by Dijkstra's
Algorithm, according to the Bellman-Ford Algorithm.

As a result, for the given map, the Bellman-Ford and Dijkstra's algorithms provide the same shortest paths.
Though Dijkstra's Algorithm cannot handle negative edge weights, Bellman-Ford Algorithm can, and
Dijkstra's Algorithm is typically quicker than it for sparse graphs.

35
Activity 7
The development team in the case study of creating a mobile device's firmware is made up of programmers
with a variety of backgrounds, including iOS and Java. One of the developers brought up the issue that
algorithms need to be language independent, even though there might be syntactic variations when
constructing programs using various programming languages. This is a crucial topic because it emphasizes
how critical it is to employ data structures that are independent of programming languages when
developing firmware.
When developing the firmware, using data structures independent of programming languages has various
advantages:
 Portability: Code for data structures that are independent of programming languages can be readily
transferred to other programming languages, facilitating code reuse across various firmware
components or projects. This can enhance the consistency and maintainability of the code while also
saving time and effort during the development process.
 Reusability: Data structures that are independent of programming languages can be reused in many
firmware components or projects, saving time and effort throughout the development process. This is
so that they don't have to be implemented again every time they are needed; instead, the data
structures can be implemented once and then utilized in many contexts.
 Maintainability: Since programming language independent data structures aren't dependent on any
one programming language, they may be simpler to maintain. This implies that rather than needing
to make changes in several locations, updates to the data structures can be done once and then
propagated to every location where the data structures are used. This can enhance the code's
consistency and maintainability.

36
37
References
David Loshin. (2021, March). Definition Data structures. Retrieved from TechTarget:
https://www.techtarget.com/searchdatamanagement/definition/data-structure
Kochar, A. (2023, December 28). PrepBytes Blog. Retrieved from PrepBytes Blog:
https://www.prepbytes.com/blog/data-structure/abstract-data-type-adt-in-data-structure/
Muskan. (n.d.). Geeks for Geeks. Retrieved from Geeks for Geeks: https://www.geeksforgeeks.org/most-
important-type-of-algorithms/
Unknown. (n.d.). Programiz. Retrieved from Programiz: https://www.programiz.com/dsa/data-structure-
types

38

You might also like