0% found this document useful (0 votes)
14 views22 pages

Data Structures and Algorithms (Dsa Aathif Musthafa) 1

Uploaded by

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

Data Structures and Algorithms (Dsa Aathif Musthafa) 1

Uploaded by

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

2023

DATA STRUCTURES AND ALG


1022535
Aathif Musthafa
DATA STRUCTURES AND ALGORITHMS

Contents
LO1..............................................................................................................................................................3
PART 1......................................................................................................................................................3
P1 Create a design specification for data structures explaining the valid operations that can be
carried out on the structures...............................................................................................................3
Stack ADT.............................................................................................................................................3
Queue ADT..........................................................................................................................................5
Linked list ADT.....................................................................................................................................6
P2 Determine the operations of a memory stack and how it is used to implement function calls in a
computer.................................................................................................................................................7
LO2..............................................................................................................................................................8
P3 Using an imperative definition, specify the abstract data type for a software stack...........................8
Here`s how ADTs and software stacks are involved.................................................................................9
Abstract Data.......................................................................................................................................9
ADT Stack.............................................................................................................................................9
The software stack...............................................................................................................................9
The usage software stack's..................................................................................................................9
LO3............................................................................................................................................................10
P4 Implement a complex ADT and algorithm in an executable programming language to solve a well-
defined problem....................................................................................................................................10
ALGORITHM.......................................................................................................................................10
Test cases...............................................................................................................................................11
Adding new patients..........................................................................................................................11
Deleting Patients................................................................................................................................12
Viewing Next Patient.........................................................................................................................13
Searching for Patients........................................................................................................................13
Full Queue Exception.........................................................................................................................14
Empty Queue Exception....................................................................................................................14
LO4............................................................................................................................................................15
P5 Implement error handling and report test results............................................................................15
Error handling........................................................................................................................................15
Managing Queue Empty and Queue Full exceptions.........................................................................15

1
DATA STRUCTURES AND ALGORITHMS

P6 Discuss how asymptotic analysis can be used to assess the effectiveness of an algorithm..............15
Time Complexity Evaluation...............................................................................................................15
Omega. Notation...............................................................................................................................16
Theta Notation...................................................................................................................................16
Space Complexity Evaluation.............................................................................................................16
Algorithmic Behavior Prediction........................................................................................................16
P7 Determine two ways in which the efficiency of an algorithm can be measured, illustrating your
answer with an example........................................................................................................................17
Problem.............................................................................................................................................17
Time Complexity Analysis................................................................................................................18
Space Complexity..............................................................................................................................18
Space Complexity Analysis.................................................................................................................20
Comparison.......................................................................................................................................20
Reference..............................................................................................................................................21

Figure 1 stack...............................................................................................................................................4
Figure 2 queue.............................................................................................................................................6
Figure 3 LINKEDLIST.....................................................................................................................................8
Figure 4 : Adding New Patients..................................................................................................................13
Figure 5 CHOICING MENUE.......................................................................................................................14
Figure 6 CHOICING VIEW NEXT..................................................................................................................14
Figure 7......................................................................................................................................................15
Figure 8 Searching for Patients..................................................................................................................15
Figure 9 : TIME COMPLEXCITY...................................................................................................................18
Figure 10 : SPACE COMPLEXITY..................................................................................................................19

2
DATA STRUCTURES AND ALGORITHMS

LO1
PART 1

P1 Create a design specification for data structures explaining the valid operations that can be
carried out on the structures.

Stack ADT

The stack data structure adheres to the First In Last Out (LIFO) concept. The collection is the final and
initial item to be eliminated. This behavior is comparable to being able to take only the top plate from a
stack of plates.

 Push: An element is added to the top of the stack when it is pushed. After
receiving the element as input, it inserts it into the stack. The push operation
consists of the following steps:

o Check to see if the stack is full or at capacity. An overflow scenario


occurs when the stack becomes too full to include any more elements.
o Raise the stack pointer and place the new element at the top of the
stack if there is room for it.

 Pop: The pop operation removes the element at the top of the stack. It doesn't
need any input and returns the element that is being removed. The pop
procedure consists of the following steps:
o Check to see if there are any elements on the stack or not. An
underflow condition occurs when the stack is empty because there
are no elements to remove.
o If the stack is not empty, retrieve the element at the top of the
stack, decrease the stack pointer, and remove the element from the
stack.

 Peek: You can examine the element at the top of the stack without taking it
down by using the peek method. The stack is not changed; only the top member
is returned. The peek operation consists of the following steps:

o Ascertain whether the stack is clear. If it is, there are no items to


peek at, which results in an underflow condition.
o If the top element in the stack is not empty, retrieve it without
modifying the stack itself.

3
DATA STRUCTURES AND ALGORITHMS

 Size: The number of elements that are presently on the stack is obtained by the size
operation. It doesn't modify the stack; instead, it provides details about its current
state.
 The size can be found by looking at the value of the stack pointer. The difference
between the stack pointer's initial position and the number of elements in the stack
is what counts.
 Is Empty: This function ascertains if the stack is empty. To show whether the stack is
empty, it returns a Boolean result (true is Empty or false). The stack is considered
empty if it contains no elements and the stack pointer is at the beginning.
 ISFULL: This function ascertains if the stack is fully loaded. The stack generates a
Boolean result (yes or false) indicating whether it has reached its maximum capacity.
It is not possible to add more items to a full stack.

Figure 1 stack

4
DATA STRUCTURES AND ALGORITHMS

Queue ADT

First In First Out, or FIFO, is the guiding concept of queue data structures. It is a group of elements in
which the first element to be eliminated is the one that was inserted first. This conduct is comparable to
a queue of individuals waiting in queue, where the first person to arrive is the first to go.

 Enqueue (Push): During the enqueue process, an element is added to the back or end of the
queue. The element is added to the queue after being accepted as input. The following steps are
involved in the enqueue operation:

o Check to see if the queue is full or has reached its capacity. Overflow occurs when the
queue is full and cannot accommodate any more elements.

o Add the new element at the end if the line is not already full.

 Dequeue (Pop): The front or first component in the queue is removed when a dequeue action
is carried out. It doesn't need any input and returns the element that is being removed. The
following steps are involved in the dequeue operation:

o Confirm that there are no more components in the queue. An underflow condition
occurs when the queue is empty because there are no elements to be deleted.

o If the element at the front of the queue is not empty, remove it and shift the other
components up front to maintain the order.

 Peek: The peek action allows you to view the first or frontmost element in the queue without
removing it from the queue. It doesn't alter the queue; it only returns the element at the front.

o Make sure there isn't a line. If it is, there are no items to peek at, which results in an
underflow condition.

o If the element at the front of the queue is not empty, get it without altering the queue
structure.

 Size: The size operation displays the current number of elements in the queue. It doesn't modify
the queue; instead, it provides details about its present status.It is possible to calculate the size
by counting the elements in the queue.

 is Empty: This function ascertains if the queue is empty. Whether the queue is empty is
indicated by the Boolean value (true or false) that is returned. The queue is considered empty if
there are no elements in it.

5
DATA STRUCTURES AND ALGORITHMS

 IS FULL: This function establishes if the queue is at capacity. The queue generates a Boolean
result (yes or false) indicating whether it has reached its maximum capacity. It is not possible to
add further elements if the queue is full.

 The fullness of the queue is determined by its underlying implementation. It could be based on
the maximum element capacity of the queue or the amount of RAM that is immediately
accessible.

Figure 2 queue

Linked list ADT

An element is stored in every independent node of a linear data structure called a linked list. Each node
contains the data as well as a reference to the node that comes after it in the list. Unlike arrays, which
keep elements in sequential memory locations, linked lists use dynamic memory allocation and can grow
or shrink as needed.

 Insert (Push): When a linked list is inserted, a new element is added. When adding at the
beginning of the list, it is similar to pushing in a stack or queue. The following steps are involved
in the insert operation:
o To accommodate the additional element, a new node needs to be made.
o Modify the new node's data to include the necessary element.
o Set the next pointer of the new node to the top node of the list.
o Move the linked list's head pointer to point to the new node, making it the first node.

 Delete (Pop): A linked list element is removed with the delete action. In a stack or queue, the
pop operation is comparable to removing something from the top of the list. The following steps
are involved in the deletion process:

o Check to see if the linked list is empty. If it is empty, there are no elements to delete,
hence the action cannot be completed.

6
DATA STRUCTURES AND ALGORITHMS

o Update the head pointer to point to the next node in the list in order to remove the first
node if the linked list is not empty.

 Peek: The peek operation allows you to view the value of a particular node without making any
changes to the linked list. There is no need to alter the linked list's structure. Easily access the
desired node's data.

 Size: The size operation returns the current element count of the linked list. To determine the
size, count each node you encounter as you proceed from the first node to the last node in the
linked list.

 "ISEMPTY The operation "is Empty" ascertains if the linked list is empty. The linked list generates
a Boolean result (true or false) indicating whether any nodes are present. The solution can be
found by looking to check if the head pointer is null. If the head pointer is null, the list is empty.

 is Full: The idea that a linked list is "full" is meaningless because nodes can be dynamically
allocated as needed. As a result, there is no isFull operation in a linked list ADT.

 The basic functionality of a linked list ADT is provided by these actions together, which include
adding and deleting items, peeking at node values, calculating the size, and determining if the
linked list is empty.

Figure 3 LINKEDLIST

P2 Determine the operations of a memory stack and how it is used to implement function
calls in a computer.

7
DATA STRUCTURES AND ALGORITHMS

In computer programming, the memory stack—also called the call stack or execution stack—is a data
structure that contains information about the commands and activities that are currently in progress. It
manages memory allocation and control flow while programmes are operating.

Function Calls: When a function is called within a programme, the system allots a certain amount of
memory known as a stack frame or activation record for that function. This stack frame contains the
function arguments, local variables, and return address.

Stack Frame: A memory block reserved for the function that is now in use is all that the stack frame is.
Its three main sections are the return address, function parameters, and local variables.

Local Variables: Variables defined inside a function that are only utilised inside its boundaries are
referred to as local variables. When the function is called, they are created, saved on the stack frame,
and then removed when the function is no longer invoked.

Function arguments: Values are passed to a function as arguments when it is called. They are stored in
the stack frame and can also be retrieved within the function.

Return Address: The return address is the memory address that the function was called from. In order
for the programme to know where to go back and restart execution when the function has completed
running, it is saved in the stack frame.

Stack Pointer: A unique register that monitors the top of the stack is called the stack pointer. It shows
the position of the current stack frame in relation to the subsequent stack frame.

Stack operations: When functions are called and returned, the stack grows and shrinks. When a
function is called, a new stack frame is allocated to the stack and its location is indicated by an increase
in the stack pointer. The stack pointer is decremented to remove the function's stack frame off the stack
after it has finished.

Stack Overflow and Underflow: To avoid stack overflow and underflow, it's important to keep in mind
that the stack has a finite size. A stack overflow occurs when there are too many function calls and the
stack reaches its limit, causing a runtime error. Conversely, when more stack frames are popped than
pushed, an error known as a stack underflow occurs.

The memory stack plays a major role in controlling function calls, local variables, and control flow inside
a programmed. Knowing how it works is essential for efficient memory management and avoiding stack-
related issues.

LO2

P3 Using an imperative definition, specify the abstract data type for a software stack.

8
DATA STRUCTURES AND ALGORITHMS

In computer science, software stacks and Abstract Data Types (ADTs) are closely related ideas. One type
of ADT that follows the Last-In-First-Out (LIFO) principle is software stacks. Another name for them is
stack data structures. Software stacks are the physical embodiment of ADTs, while ADTs provide a high-
level interface for manipulating data structures.

Here`s how ADTs and software stacks are involved.

Abstract Data

 ADTs are conceptual models that specify a collection of actions or behaviours on a certain data
structure without going into the underlying workings of the implementation. The primary focus
of ADTs is the external interface, which includes the scope of operations that may be performed
on the data structure and the limitations imposed on those actions. ADTs provide a high degree
of abstraction and are independent of languages, so users may work with data structures
without worrying about the implementation at the foundation. ADT examples include stacks,
queues, lists, trees, and graphs.

ADT Stack

 Stack ADTs are ADTs that follow the Last-In-First-Out (LIFO) concept. The two primary operations
it supports are pushing an element to the top of the stack and popping an element from the top
of the stack. Oftentimes, the stack ADT provides additional operations like peek, which allows
you to view the top element without deleting it, and isEmpty, which checks if the stack is empty.
Stack ADT pays more attention to the constraints and behaviour of the operations than it does to
the internal storage of the elements.

The software stack.

 A useful implementation of the stack A stack data structure, or software stack, is called ADT.In
software, stacks are usually implemented using arrays or linked lists. The internal
implementation of a software stack entails monitoring the top of the stack and dynamically
modifying it in response to pushed or popped pieces. A software stack also includes memory
management, which includes dynamically allocating or deallocating memory for elements as
they are added or withdrawn.

The usage software stack's

 Programming languages and a wide variety of computer systems use software stacks.
Programming languages use them to manage nested function calls, local variables, and function

9
DATA STRUCTURES AND ALGORITHMS

calls. Software stacks are also utilized for expression evaluation, parsing, memory management
(including call and runtime stacks), undo/redo operations, backtracking algorithms, and other
tasks. Because of its LIFO trait, a software stack is appropriate in scenarios where the elements
that have been introduced most recently are the ones that are of interest.

To summarise, abstract data types (ADTs) provide a high-level interface and behavioural restrictions for
interacting with data structures, while software stacks are a tangible implementation of the stack ADT.
Software stacks store their components in arrays or linked lists and follow the Last-In-First-Out principle.
They are used for a range of system-related and programming activities, and they process information
efficiently by following the LIFO behaviour.

LO3

P4 Implement a complex ADT and algorithm in an executable programming language to


solve a well-defined problem.

ALGORITHM

 Create a class named Main that contains the main method, which is where the programme
starts.
 To manage the patient appointment queue, create an instance of the appointmentQueue class
within the main method.
 Make a Scanner object in order to read user input from the console.
 Use the while (true) statement to start an infinite loop that will show the user a menu of
options.
 Inside the loop, show the user's menu options:

o Add patients.
o View patient
o Delete patient that was checked.
o Search.
o QUIT.

 The user's selection is read from the console by the scanner.nextInt(), after which save the
outcome in a choice variable.
 Make use of an if-else statement to connect with the user's selection:
 If option == 1, execute the further steps:

10
DATA STRUCTURES AND ALGORITHMS

 Request that the user input the patient's details, such as name, age, phone number, address,
and appointment number, using a scanner.nextLine(), and store each one in a distinct variable
after that.
 Use the addPatients function for the appointment.Use the queue class to add the patient to the
appointment queue.
 The details of the patient's appointment should be displayed on the console.
 Dial the appointment's deletepatient method.If option == 2, the queue class will remove the
front patient—the one who has been examined or consulted—from the queue.
 Dial the view of the appointment. Patient’s approach if choice === 3 The queue class will show
the name of the patient at the front of the queue (the one who will be inspected or consulted
next).
 The user is prompted to provide the name of a patient to be searched for using a scanner if
choice == 4.next().
 Call the search Patient function of the appointmentQueue class to find the patient's position in
the queue and display it on the console.
 The programmed will terminate by turning off the scanner, printing a last message, and breaking
out of the loop if option equals 5.
 view Patients: Take care of the case and put the patient's name at the front of the queue when
the queue is empty.
 search Patient: Locate a patient's position in the patient queue, then provide back the location. If
the patient is not found, return -1.
 The application will interact with the user to manage patient appointments after the Main class
has been constructed and launched, or until the user chooses to stop it.

Test cases.

11
DATA STRUCTURES AND ALGORITHMS

Adding new patients


 Pick the first choice from the menu.
 Enter the patient's information, including name, age, address, phone number, appointment
number, and name of the consulting physician.
 Check that the patient's appointment information is shown accurately.

Figure 4 : Adding New Patients

Deleting Patients
 Select the second item on the menu.
 Check that the patient at the head of the line has been removed and that the relevant
messages have been shown once the queue is empty.

12
DATA STRUCTURES AND ALGORITHMS

Figure 5 CHOICING MENUE

Viewing Next Patient


 Select the third item on the menu.
 Check to see if the patient's name is shown at the front of the queue and if the queue
displays the necessary messages when it is empty.

Figure 6 CHOICING VIEW NEXT

Searching for Patients


 Select the fourth item on the menu.
 In the queue, type the name of a current patient.
 Check that the patient's actual location in the queue is presented.
 Put the name of a patient in the queue that doesn't exist.

13
DATA STRUCTURES AND ALGORITHMS

 Check to see if the patient's location is indicated by a -1.

Figure 8 Searching for Patients Figure 7

Full Queue Exception


 Continue adding patients until the wait reaches 1000 people.
 Ascertain whether a "Queue is full." When attempting to add new patients, the notice
"Cannot add more patients." appears.

Empty Queue Exception


 Till the queue is empty, remove every patient from it.
 Make sure a "Queue is empty." When attempting to delete or view patients from an empty
queue, the message "No patients to delete or view." appears.

LO4

P5 Implement error handling and report test results.

14
DATA STRUCTURES AND ALGORITHMS

Error handling

Managing Queue Empty and Queue Full exceptions.

 We define two distinct exception types, QueueFullException and QueueEmptyException, for the
appointment Queue class.
 The add Patients method throws a QueueFullException with the relevant error message when it
tries to add a patient to a full queue.
 We throw a QueueEmptyException with the relevant error message when we try to delete or see
patients from an empty queue using the delete patient and view Patients methods.
 These custom exceptions allow us to handle special cases in the code and provide the user with
informative error messages.

P6 Discuss how asymptotic analysis can be used to assess the effectiveness of an


algorithm.

Asymptotic analysis is a powerful method for evaluating the efficacy and efficiency of an algorithm. It
allows us to understand how an algorithm's performance scales with input size and provides us with a
high-level perspective of an algorithm's time and space complexity. With the use of asymptotic analysis,
we may decide with confidence which method is appropriate to apply in a certain scenario or set of
circumstances. This is one way that asymptotic analysis helps determine the effectiveness of a method.

Time Complexity Evaluation

 We can evaluate the link between the execution time and input size of an algorithm through
asymptotic analysis. It provides us with a "big picture" understanding of the algorithm's efficacy
rather than focusing on exact execution times that could vary depending on various inputs or
technological advancements.

Big O indication

 It is widely used to display an algorithm's maximum time complexity. For example, an algorithm
with an O(n) time complexity works well with small to moderately large inputs because the
algorithm's execution time increases linearly with the input's size. However, as the input size
greatly increases, the method's performance could become problematic.

15
DATA STRUCTURES AND ALGORITHMS

Omega. Notation

 Omega notation indicates the lower bound of the temporal complexity of an algorithm. It
provides details on the best possible performance of the algorithm. Regardless of the quantity
of the input, an algorithm with constant time complexity, or one with an omega notation of 1,
for example, is incredibly efficient.

Theta Notation.

 This represents both the upper and bottom bounds of the algorithm's temporal complexity
growth, providing a tight bound. An algorithm with theta notation of (n) runs neither faster nor
slower; instead, its running time grows linearly with the amount of input.

Space Complexity Evaluation

 We can also understand how an algorithm's memory requirements increase with the volume of
input by using asymptotic analysis. Similar to temporal complexity analysis, space complexity
analysis describes the maximum amount of space required for a process using big O notation.

Algorithmic Behavior Prediction

 By using asymptotic analysis, we can predict the algorithm's behavior even in the case of very
large input sizes without ever running the method. This is especially useful when dealing with
algorithms that may need a lot of time or space for large inputs, as it helps identify possible
bottlenecks.
 To sum up, asymptotic analysis offers crucial insights into the effectiveness and scalability of
algorithms. It helps choose the best solution for a particular task by taking into account
variables including expected input sizes, computing efficiency overall, and time and space
constraints.

P7 Determine two ways in which the efficiency of an algorithm can be measured,


illustrating your answer with an example.

Problem
Computing the Sum of an Array

16
DATA STRUCTURES AND ALGORITHMS

Let's consider a simple problem where we want to compute the sum of all elements in an array of
integers.

Time Complexity.

An algorithm's time complexity describes how many operations it executes as a function of the amount
of input. It helps us understand how the algorithm's execution time grows as the size of the inputs rises.

Algorithm 1 : Linear sum

Linear sum is a straightforward algorithm that iterates through each element in the array and adds it to a
running sum.

Figure 9Computing the Sum of an Array(linear sum).

17
DATA STRUCTURES AND ALGORITHMS

Time Complexity Analysis.

For each element in the array, we conduct a constant-time operation (addition) in the linear algorithm.
The number of operations increases linearly as the size of the array (n) increases. As a result, the
temporal complexity of this technique is O(n), where n is the number of array members.

Space Complexity

The amount of memory used by an algorithm in relation to the size of the input. It assists us in
determining how much additional memory the algorithm requires for execution.

Algorithm 2 : Constant Space Sum

Constance space sum is an optimized algorithm that computes the sum without using additional
data structures

18
DATA STRUCTURES AND ALGORITHMS

Figure 10 Constant Space Sum

Space Complexity Analysis.

In the constant space sum algorithm, the running total is only stored in a single variable, sum. The amount
of memory used is constant regardless of the input size. As a result, this algorithm has an O(1) space
complexity, which denotes constant space usage.

Comparison

19
DATA STRUCTURES AND ALGORITHMS

Both methods produce the same outcome, which is computing an array's sum. But their levels of
effectiveness vary.
Given that the number of operations grows linearly with input size, the Linear Sum algorithm is less
effective for larger arrays because its time complexity is O(n).
The fastest solution to this issue is the Constant Space Sum algorithm, which has an O(n) time
complexity. Additionally, it has a space complexity of O(1), which means that regardless of the input size,
it uses a fixed amount of memory, making it extremely memory efficient.

The best algorithm to use will depend on the particulars of the problem, the size of the expected input,
and whether it is more important to optimize for time or space efficiency.

Reference

Abstract data types (2023) GeeksforGeeks.


Available at: https://www.geeksforgeeks.org/abstract-data-types/ (Accessed: 05 July 2023).

Stack ADT in Data Structures (no date) Online Courses and eBooks Library.
Available at: https://www.tutorialspoint.com/stack-adt-in-data-structures (Accessed: 10 July 2023).

Abstract data types (2023) GeeksforGeeks.


Available at: https://www.geeksforgeeks.org/abstract-data-types/ (Accessed: 31 July 2023).

20
DATA STRUCTURES AND ALGORITHMS

Trivedi, A. (2021) Space complexity in data structure, Scaler Topics.


Available at: https://www.scaler.com/topics/data-structures/space-complexity-in-data-structure/
(Accessed: 31 July 2023).

https://www.coursehero.com/file/p2262bp6/2-Demonstrate-how-the-implementation-of-an-
ADTalgorithm-solves-a-well-defined/

21

You might also like