Unit 19 Dsa Assignment
Unit 19 Dsa Assignment
Assessor Internal
Verifier
Unit 19: Data Structures and Algorithms
Unit(s)
Assignment title
A.M.Belicks
Student’s name
List which assessment Pass Merit Distinction
criteria the Assessor has
awarded.
Programme Leader
Date
signature (if required)
Higher Nationals - Summative Assignment Feedback Form
Student Name/ID
LO3 Discuss the importance and dynamics of working within a team and the impact of team working in
different environments
Pass, Merit & Distinction P4 P5 M4 D3
Descripts
LO4 Examine the need for Continuing Professional Development (CPD) and its role within the workplace
and for higher level learning
Pass, Merit & Distinction P6 P7 M5 D4
Descripts
Resubmission Feedback:
Assignment Feedback
Action Plan
Summative feedback
Feedback: Student to Assessor
1. A cover page or title page should be attached to your assignment. Use page 1 of this assignment
brief as your cover page and make sure all details are accurately filled.
2. The entire assignment brief should be attached as the first section of your assignment.
3. The assignment should be prepared using a word processing software.
4. The assignment should be word processing in an A4 sized paper.
5. Allow 1” margin on top, bottom and right sides of the paper and 1.25” on the left side (for
binding).
1. The font size should be 12 point, and should be in the style of Time New Roman.
2. Set line spacing to 1.5. Justify all paragraphs.
3. Ensure that all headings are consistent in terms of size and font style.
4. Use footer function on the word processor to insert your name, unit, assignment no, and page
number on each page. This is useful if individual sheets get detached from the submission.
5. Use the spell check and grammar check function of the word processing application to review
the use of language on your assignment.
Important Points:
1. Carefully check carefully the hand in date and the instructions given with the assignment. Late
submissions will not be accepted.
2. Ensure that sufficient time is spent to complete the assignment by the due date.
3. Do not wait till the last minute to get feedback on the assignment. Such excuses will not be
accepted for late submissions.
4. You must be responsible for efficient management of your time.
5. If you are unable to hand in your assignment on time and have valid reasons such as illness, you
may apply (in writing) for an extension.
6. Failure to achieve at least a PASS grade will result in a REFERRAL grade.
7. Non-submission of work without valid reasons will lead to an automatic REFERRAL. You will
then be asked to complete an alternative assignment.
8. If you use other people’s work or ideas in your assignment, it must be properly referenced, using
the HARVARD referencing system, in your text or any bibliography. Otherwise, you’ll be found
guilty of committing plagiarism.
9. If you are caught plagiarising, your grade will be reduced to a REFERRAL or at worst, you could
be excluded from the course.
Student Declaration
I hereby, declare that I know what plagiarism entails, namely to use another’s work and to present it as
my own without attributing the sources in the correct form. I further understand what it means to copy
another’s work.
[email protected] 17/02/2021
Student’s Signature: Date:
(Provide E-mail ID) (Provide Submission Date)
Higher National Diploma in Business
Assignment Brief
Submission format
The submission should be in the form of a report, which contains code snippets (which must be
described well), text-based descriptions, and diagrams where appropriate. References to external
sources of knowledge must be cited (reference list supported by in-text citations) using the
Harvard Referencing style.
LO1. Examine abstract data types, concrete data structures and algorithms.
LO2. Specify abstract data types and algorithms in a formal notation.
LO3. Implement complex data structures and algorithms.
LO4. Assess the effectiveness of data structures and algorithms.
Assignment Brief and Guidance:
Scenario
‘XYZ’ hotel chain has 100 banquet halls island wide. Any hotel has minimum one banquet hall to
maximum 5 halls. It provides online hotel banquet hall reservation facilities to their customers.
The reservation system uses a waiting list of the selected banquet halls.
Each banquet hall has unique id, name, location, maximum number guests, reservation date
and the three menu prices. Customer can search a banquet hall with the location, reservation
date and the number of guests. According to the hotel chain rules and regulations, when a
possible match between reservation and the banquet hall is found the customer is contacted
via email or SMS and informed. If customer is not responding within a day, he or she is placed
back in the waiting list and must wait again for another hall.
Task 2: Implement the above scenario using the selected data structure and its valid operations
for the design specification given in task 1. Use suitable error handling where appropriate. Test
the application using suitable test cases and illustrate the system. Provide evidence of the test
cases and the test results.
Task 3: Determine the operations of a memory stack and how it is used to implement function
calls related to the above scenario.
Task 4: Sort the banquet hall list and display from the smallest to largest based on the
maximum number of seating arrangements that can be done.
Sort the banquets halls with two different sorting algorithms and compare the performances of
those two algorithms.
Task 5: There are 8 hotels available in the Southern district in Sri Lanka. A customer plans to
visit all of these eight hotels through the shortest path within a day.
Analyse the operation, using illustrations, of two shortest path algorithms, showing how it
operates using a sample graph.
Task 6: Banquet hall details are stored from oldest to newest hall. The customer should be able
to find from the newest to the oldest banquet hall added to the hotel chain.
Using an imperative definition, specify the abstract data type for the above scenario.
Examine the advantages of encapsulation and information hiding when using an ADT selected
for the above scenario.
Object orientation is a paradigm where a computer program functions by objects calling the
methods of other objects, which ultimately produces program behaviour. It makes
programming simple, readable, and makes programs maintainable. Imperative ADTs are basis
for object orientation. Do you agree? Justify your answer.
Task 7: Implement the above scenario using the selected complex ADT.
Demonstrate how the implementation of an ADT/algorithm solves the above problem.
Critically evaluate the complexity of an implemented ADT/algorithm.
Determine the different ways in which the efficiency of an algorithm can be measured,
illustrating your answer the algorithm which you have developed.
Task 8: Asymptotic analysis can be used to assess the effectiveness of an algorithm. How to use
the Asymptotic analysis for the scenario given in task 7?
What sort of trade-offs exists when you use a ADT for implementing programs? Describe the
benefits of using independent data structures for implementing programs.
Grading Rubric
15
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
LO2. Specify abstract data types and algorithms in a
formal notation.
16
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
M4 Demonstrate how the implementation of an
ADT/algorithm solves a well-defined problem.
D3 Critically evaluate the complexity of an implemented
ADT/algorithm.
17
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
18
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Task 1: Which data structure can be used, when simulating the above scenario. What are the
valid operations that can be carried out on this data structure?
Queue
A Queue is a First in First Out (FIFO) data structure. It models a queue in real-life. Yes,
the one that you might have seen in front of a movie theater, a shopping mall, a metro, or
a bus.
Just like queues in real life, new elements in a Queue data structure are added at the back and
removed from the front. A Queue can be visualized as shown in the figure below.
The process of adding an element at the back of the Queue is called Enqueue, and the process
of removing an element from the front of the Queue is called Dequeue.
Java provides a Queue interface which is part of Java’s collections framework. The figure
below depicts the position of Queue interface in Collections hierarchy -
19
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
A Queue in Java is just an interface. We need a concrete implementation of the Queue
interface to work with, in our programs.
As shown in the diagram above, the LinkedList class implements the Queue interface and
therefore it can be used as a Queue.
Here I proposed queue data structure for XYZ hotel system because XYZ hotel system
required a waiting list program.
20
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
The waiting list program should include:
If customer is not responding with in a day, he/she is placed back into the waiting list.
If customer request any changes or reject the reservation, delete the reservation and
insert it to the back of the queue.
Above system requirements are elements of the FIFO (First in First Out) Methodology. This
is the main reason to I recommend queue data structure is most suitable for this system.
in here, if you booking banquet hall, and are you in the first of the queue then you will be the
first one to get the booking. Same is the case with Queue data structure. Data inserted first,
will leave the queue first.
in queue process:
enqueue ()
This function defines the operation for adding an element into queue
dequeue ()
This function defines the operation for removing an element from queue.
Search
Searching is an operation or a technique that helps finds the place of a given element or value
in the list.
Front
Rear
Enqueue
A queue always maintains two pointers, there are front and rear, steps for the enqueue
reservation in the queue
Step 3 – if it is not full, increment the rear pointer to point next empty space.
Step 4 - Add the reservation to the queue location where rear is pointing.
Example –
After getting a confirmation, particular reservation should remove in the waiting list. And add
to the confirm reservation.
Reservation 4 Confirmed
Rear Front
reservation
22
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Add reservation 4 to the Queue. Then first Queue is going to check reservations is full or
not.
After reservation confirmed increment the rear pointer to point next empty space, and add
the new reservation 4 to the queue. Where rear is pointing.
2. If the customer booked the temporary reservation but not respond within a day.
if customer not responding within the day, reservation should in the waiting list
3.If customer change the any requirements such as location, date or no of guests.
23
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Then reservation will remove from the confirmed reservation and it will be move to the
waiting list Reservation
24
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Rear Front
Confirmed
Reservation
Remove
Reservation 4
Add
If customer accept the reservation without any changes then customer reservation moved to
confirmed reservation from waiting list reservation and banquet hall is remove in the
available banquet hall list
Rear Front
waiting list
Reservation
Remove
25
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Add
Banquet list
Rear Front
Available Banquet
halls
Remove
Banquet 4
26
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
02. Dequeue
Accessing Hotel Reservation From queue is a process of the access the reservation where
front is pointing and remove the reservation after the access. following steps to follow for
dequeue operation.
Step 3 - If Hotel Reservation queue is not empty, access hotel reservation from front pointing
Before the function, it should check Hotel reservation, queue is empty its mean the
reservation is there or not. If empty produce the error message if not, remove the reservation
and put in to the waiting list
Rear Front
After check the function, if reservation 1 is not responding within a day and then remove
reservation 1 and provide the chance to the following reservation 2.
Rear Front
27
A.M.BELICKS
COL/E-008348 Reservation 4 Reservation 3 Reservation 2
UNIT – 19 DS
Dequeue
Reservation 1
If customer change the requirements then same progress will happen again
Init ()
If it is Empty
Check queue is empty or not (if it is empty then addition of an item possible to it, if it is not
empty then acknowledge with the message "Queue is empty")
If it is full
Check queue is full or not (if it is full then removal of an item possible to it, if it is not full
then acknowledge with the message "Queue is full")
Search
Search is a useful operation to find element or value from the list, Search mainly have to
technics
Binary Search
Linear Search
Example – Search a Hotel Banquet from the system based on requirements like Location,
Size, No of seats, etc.
Rear and Front makes easy for FIFO method, Like if customer inserted in real end and then
that exiting customer will remove from Front end , which means , which customer inserted
first that customer will remove first from the queue.
Task 2: Implement the above scenario using the selected data structure and its valid
operations for the design specification given in task 1. Use suitable error handling
where appropriate. Test the application using suitable test cases and illustrate the
system. Provide evidence of the test cases and the test results.
28
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Here I used Queue data structure for this scenario and following variable and functions I used
for the system.
OPERATIONS VARIABLES
Enqueue Rear, Front, Buff, Bool
Dequeue Front, String, return type
Init (is full) Rear, Front, Buff, Bool
Init (is empty) Rear, Front, Buff, Bool
Search Array, key, return type
Queue data structure can be implementing using array, stack, etc but using array is best way
to implement.
Initially the FRONT (head) and the REAR (tail) of the queue points at the first index of the
array (starting the index of array from 0). like I add elements to the queue, the REAR (tail)
keeps on moving ahead, it’s always pointing to the position where the next element will be
inserted, while the head remains at the first index.
29
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Add Waiting List Code
30
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Test Plan
Test plan ID 01
Brief introduction This document defines the plan for testing the Hotel
about the testing Reservation System, and this document supports the following
objectives objectives:
Testing tasks Test planning, Test design, Test development, Test execution,
Test evolution
Test deliverables Test plan, Test environment, Test summary, Test result, Test
evaluation report.
31
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Project Name: Hotel Reservation System
Test Case
Test Unit: Temporary Reservation Confirm Test designed by: A.M. Belicks
Test Case
Test unit: Temporary Reservation Not Confirmed Test designed by: A.M.Belicks
Test Case
Description: Customer change the hotel Test execution date: 2nd December
Reservation Details 2020
33
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Date,Location,Numbe ADDTemp_reservation ADDTemp_reservation Pass
r of gust Changed , Waiting list, , Waiting list,
Available banquet hal Available banquet hal
Test Case
34
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Project Name: Hotel Reservation System
Test Case
Test Case
35
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Test execution time: 4.30PM –
4.40PM
Task 3: Determine the operations of a memory stack and how it is used to implement
function calls related to the above scenario.
The computers which use Stack-based CPU Organization are based on a data structure
called stack. The stack is a list of data words. It uses Last in First Out (LIFO) access
method which is the most popular access method in most of the CPU. A register is used to
store the address of the topmost element of the stack which is known as Stack pointer (SP).
In this organization, ALU operations are performed on stack data. It means both the operands
are always required on the stack. After manipulation, the result is placed in the stack.
The main two operations that are performed on the operators of the stack are Push and Pop.
These two operations are performed from one end only.
1. Push –
This operation results in inserting one operand at the top of the stack and it decrease the
stack pointer register. The format of the PUSH instruction is:
PUSH
It inserts the data word at specified address to the top of the stack. It can be
implemented as:
//decrement SP by 1
SP <-- SP - 1
36
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
//into SP; i.e, at top of stack
2. Pop –
This operation results in deleting one operand from the top of the stack and it increase
the stack pointer register. The format of the POP instruction is:
POP
It deletes the data word at the top of the stack to the specified address. It can be
implemented as:
//increment SP by 1
SP <-- SP + 1
Operation type instruction does not need the address field in this CPU organization.
This is because the operation is performed on the two operands that are on the top of the
stack. For example:
SUB
This instruction contains the opcode only with no address field. It pops the two-top data
from the stack, subtracting the data, and pushing the result into the stack at the top.
PDP-11, Intel’s 8085 and HP 3000 are some of the examples of the stack organized
computers.
The advantages of Stack based CPU organization –
Efficient computation of complex arithmetic expressions.
Execution of instructions is fast because operand data are stored in consecutive
memory locations.
Length of instruction is short as they do not have address field.
The disadvantages of Stack based CPU organization –
37
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
The size of the program increases.
Note: Stack based CPU organization uses zero address instruction.
(geeksforgeeks,2019)
Stake Implementation
38
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
39
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Task 4: Sort the banquet hall list and display from the smallest to largest based on the
maximum number of seating arrangements that can be done.
Sort the banquets halls with two different sorting algorithms and compare the
performances of those two algorithms.
For example: The below list of characters is sorted in increasing order of their ASCII values.
That is, the character with lesser ASCII value will be placed first than the character with
higher ASCII value.
java coding
// Java program for implementation of Selection Sort
class SelectionSort
{
void sort(int arr[])
{
int n = arr.length;
40
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
// Prints the array
void printArray(int arr[])
{
int n = arr.length;
for (int i=0; i<n; ++i)
System.out.print(arr[i]+" ");
System.out.println();
}
(geeksforgeeks 2,2020)
Selection sort algorithm is 60% more efficient than bubble sort algorithm.
Selection sort algorithm is easy to implement.
Selection sort algorithm can be used for small data sets, unfortunately Insertion sort
algorithm best suitable for it.
Insertion Sort
Insertion sort is a simple sorting algorithm that works similar to the way you sort playing
cards in your hands. The array is virtually split into a sorted and an unsorted part. Values
from the unsorted part are picked and placed at the correct position in the sorted part.
41
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Algorithm
To sort an array of size n in ascending order:
1: Iterate from arr[1] to arr[n] over the array.
2: Compare the current element (key) to its predecessor.
3: If the key element is smaller than its predecessor, compare it to the elements before.
Move the greater elements one position up to make space for the swapped element.
Example:
Another Example:
12, 11, 13, 5, 6
Let us loop for i = 1 (second element of the array) to 4 (last element of the array)
i = 1. Since 11 is smaller than 12, move 12 and insert 11 before 12
11, 12, 13, 5, 6
i = 2. 13 will remain at its position as all elements in A[0..I-1] are smaller than 13
11, 12, 13, 5, 6
i = 3. 5 will move to the beginning and all other elements from 11 to 13 will move one
position ahead of their current position.
5, 11, 12, 13, 6
i = 4. 6 will move to position after 5, and elements from 11 to 13 will move one position
ahead of their current position.
5, 6, 11, 12, 13
java Coding
// Java program for implementation of Insertion Sort
class InsertionSort {
/*Function to sort array using insertion sort*/
void sort(int arr[])
{
int n = arr.length;
for (int i = 1; i < n; ++i) {
int key = arr[i];
int j = i - 1;
42
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j = j - 1;
}
arr[j + 1] = key;
}
}
System.out.println();
}
// Driver method
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };
printArray(arr);
}
(geeksforgeeks 3,2020)
Insertion sort algorithm has a linear running time of 0(n). This is because for unsorted
list a element needs to sort for every iteration.
Straight forward, insertion sort algorithm will have worst case for descending order.
(2braces 1,2021)
43
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Sorting Method implementation
44
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Here Insertion Sort performed well than selection sort, let’s compare the selection sort and
insertion sort
Definition
Insertion sort is a simple sorting algorithm that builds the final sorted list by transferring one
element at a time. Selection sort, in contrast, is a simple sorting algorithm that repeatedly
searches remaining items to find the smallest element and moves it to the correct location.
Thus, this is the main difference between insertion sort and selection sort.
Functionality
Insertion sort transfers an element at a time to the partially sorted array while selection sort
finds the smallest element and move it accordingly.
Efficiency
45
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Another difference between insertion sort and selection sort is that the insertion sort is
efficient than selection sort.
Complexity
Complexity is also a difference between insertion sort and selection sort. Insertion sort is
more complex than selection sort.
Conclusion
Insertion sort and selection sort are two sorting algorithms. Both are suitable for sorting a
small dataset. The main difference between insertion sort and selection sort is that insertion
sort performs sorting by exchanging an element at a time with the partially sorted array
while selection sort performs sorting by selecting the smallest element from the remaining
elements and by exchanging it with the element in the correct location.
(pediaa,2020)
Task 5: There are 8 hotels available in the Southern district in Sri Lanka. A customer
plans to visit all of these eight hotels through the shortest path within a day.
Analyse the operation, using illustrations, of two shortest path algorithms, showing how
it operates using a sample graph.
Dijkstra Algorithm
Dijkstra’s algorithm is very similar to Prim’s algorithm for minimum spanning tree. Like
Prim’s MST, we generate a SPT (shortest path tree) with given source as root. We maintain
two sets, one set contains vertices included in shortest path tree, other set includes vertices
not yet included in shortest path tree. At every step of the algorithm, we find a vertex which
is in the other set (set of not yet included) and has a minimum distance from the source.
Below are the detailed steps used in Dijkstra’s algorithm to find the shortest path from a
single source vertex to all other vertices in the given graph.
Algorithm
1) Create a set sptSet (shortest path tree set) that keeps track of vertices included in
shortest path tree, i.e., whose minimum distance from source is calculated and
finalized. Initially, this set is empty. 2) Assign a distance value to all vertices in the
input graph. Initialize all distance values as INFINITE. Assign distance value as 0 for
the source vertex so that it is picked first.
46
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
…. a) Pick a vertex u which is not there in sptSet and has minimum distance value.
…. b) Include u to sptSet.
….c) Update distance value of all adjacent vertices of u. To update the distance values, iterate
through all adjacent vertices. For every adjacent vertex v, if sum of distance value of u (from
source) and weight of edge u-v, is less than the distance value of v, then update the distance
value of v.
The set sptSet is initially empty and distances assigned to vertices are {0, INF, INF, INF,
INF, INF, INF, INF} where INF indicates infinite. Now pick the vertex with minimum
distance value. The vertex 0 is picked, include it in sptSet. So sptSet becomes {0}. After
including 0 to sptSet, update distance values of its adjacent vertices. Adjacent vertices of 0
are 1 and 7. The distance values of 1 and 7 are updated as 4 and 8. Following subgraph
shows vertices and their distance values, only the vertices with finite distance values are
shown. The vertices included in SPT are shown in green colour.
Pick the vertex with minimum distance value and not already included in SPT (not in
sptSET). The vertex 1 is picked and added to sptSet. So sptSet now becomes {0, 1}. Update
the distance values of adjacent vertices of 1. The distance value of vertex 2 becomes 12.
47
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Pick the vertex with minimum distance value and not already included in SPT (not in
sptSET). Vertex 7 is picked. So sptSet now becomes {0, 1, 7}. Update the distance values of
adjacent vertices of 7. The distance value of vertex 6 and 8 becomes finite (15 and 9
respectively).
Pick the vertex with minimum distance value and not already included in SPT (not in
sptSET). Vertex 6 is picked. So sptSet now becomes {0, 1, 7, 6}. Update the distance values
of adjacent vertices of 6. The distance value of vertex 5 and 8 are updated.
We repeat the above steps until sptSet does include all vertices of given graph. Finally, we
get the following Shortest Path Tree (SPT).
class ShortestPath {
// A utility function to find the vertex with minimum distance value,
// from the set of vertices not yet included in shortest path tree
static final int V = 9;
int minDistance(int dist[], Boolean sptSet[])
{
// Initialize min value
int min = Integer.MAX_VALUE, min_index = -1;
return min_index;
}
49
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
// Find shortest path for all vertices
for (int count = 0; count < V - 1; count++) {
// Pick the minimum distance vertex from the set of vertices
// not yet processed. u is always equal to src in first
// iteration.
int u = minDistance(dist, sptSet);
// Driver method
public static void main(String[] args)
{
/* Let us create the example graph discussed above */
int graph[][] = new int[][] { { 0, 4, 0, 0, 0, 0, 0, 8, 0 },
{ 4, 0, 8, 0, 0, 0, 0, 11, 0 },
{ 0, 8, 0, 7, 0, 4, 0, 0, 2 },
{ 0, 0, 7, 0, 9, 14, 0, 0, 0 },
{ 0, 0, 0, 9, 0, 10, 0, 0, 0 },
{ 0, 0, 4, 14, 10, 0, 2, 0, 0 },
{ 0, 0, 0, 0, 0, 2, 0, 1, 6 },
{ 8, 11, 0, 0, 0, 0, 1, 0, 7 },
{ 0, 0, 2, 0, 0, 0, 6, 7, 0 } };
ShortestPath t = new ShortestPath();
t.dijkstra(graph, 0);
}
}
(geeksforgeeks 3,2020)
50
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Dijkstra implementation
51
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Relaxation Algorithm
The single - source shortest paths are based on a technique known as relaxation, a method
until the upper bound equivalent the shortest - path weight. For each vertex v ∈ V, we
that repeatedly decreases an upper bound on the actual shortest path weight of each vertex
maintain an attribute d [v], which is an upper bound on the weight of the shortest path from
source s to v. We call d [v] the shortest path estimate.
After initialization, π [v] = NIL for all v ∈ V, d [v] = 0 for v = s, and d [v] = ∞ for v ∈ V -
{s}.
The development of relaxing an edge (u, v) consists of testing whether we can improve the
shortest path to v found so far by going through u and if so, updating d [v] and π [v]. A
52
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
relaxation step may decrease the value of the shortest - path estimate d [v] and updated v's
predecessor field π [v].
Fig: Relaxing an edge (u, v) with weight w (u, v) = 2. The shortest-path estimate of each
vertex appears within the vertex.
(b) Here, v. d < u. d + w (u, v) before relaxing the edge, and so the relaxation step leaves
v. d unchanged.
53
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
RELAX (u, v, w)
1. If d [v] > d [u] + w (u, v)
2. then d [v] ← d [u] + w (u, v)
3. π [v] ← u
(javatpoint,2020)
Task 6: Banquet hall details are stored from oldest to newest hall. The customer should be
able to find from the newest to the oldest banquet hall added to the hotel chain.
Using an imperative definition, specify the abstract data type for the above scenario.
Examine the advantages of encapsulation and information hiding when using an ADT
selected for the above scenario.
Object orientation is a paradigm where a computer program functions by objects calling the
methods of other objects, which ultimately produces program behaviour. It makes
programming simple, readable, and makes programs maintainable. Imperative ADTs are
basis for object orientation. Do you agree? Justify your answer.
The definition of ADT only mentions what operations are to be performed but not how these
operations will be implemented. It does not specify how data will be organized in memory
and what algorithms will be used for implementing the operations. It is called “abstract”
because it gives an implementation-independent view. The process of providing only the
essentials and hiding the details is known as abstraction.
54
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
The user of data type does not need to know how that data type is implemented, for example,
we have been using Primitive values like int, float, char data types only with the knowledge
that these data type can operate and be performed on without any idea of how they are
implemented. So, a user only needs to know what a data type can do, but not how it will be
implemented. Think of ADT as a black box which hides the inner structure and design of the
data type. Now we’ll define three ADTs namely List ADT, Stack ADT, Queue ADT.
List ADT
The data is generally stored in key sequence in a list which has a head
structure consisting of count, pointers and address of compare function needed
to compare the data in the list.
55
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
The List ADT Functions is given below:
56
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
A list contains elements of the same type arranged in sequential order and
following operations can be performed on the list.
get() – Return an element from the list at any given position.
insert() – Insert an element at any position of the list.
remove() – Remove the first occurrence of any element from a non-
empty list.
removeAt() – Remove the element at a specified location from a non-
empty list.
replace() – Replace an element at any position by another element.
size() – Return the number of elements in the list.
isEmpty() – Return true if the list is empty, otherwise return false.
isFull() – Return true if the list is full, otherwise return false.
Stack ADT
57
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
In Stack ADT Implementation instead of data being stored in each node, the
pointer to data is stored.
The program allocates memory for the data and address is passed to the stack
ADT.
The head node and the data nodes are encapsulated in the ADT. The calling
function can only see the pointer to the stack.
The stack head structure also contains a pointer to top and count of number of
entries currently in stack .
A Stack contains elements of the same type arranged in sequential order. All operations
take place at a single end that is top of the stack and following operations can be
performed:
push() – Insert an element at one end of the stack called top.
pop() – Remove and return the element at the top of the stack, if it is not empty.
peek() – Return the element at the top of the stack without removing it, if the
stack is not empty.
size() – Return the number of elements in the stack.
isEmpty() – Return true if the stack is empty, otherwise return false.
isFull() – Return true if the stack is full, otherwise return false.
Queue ADT
The queue abstract data type (ADT) follows the basic design of the stack
abstract data type.
58
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Each node contains a void pointer to the data and the link pointer to the next
element in the queue. The program’s responsibility is to allocate memory for
storing the data.
A Queue contains elements of the same type arranged in sequential order. Operations take
place at both ends, insertion is done at the end and deletion is done at the front. Following
operations can be performed:
enqueue() – Insert an element at the end of the queue.
dequeue() – Remove and return the first element of the queue, if the queue is not
empty.
peek() – Return the element of the queue without removing it, if the queue is not
empty.
size() – Return the number of elements in the queue.
isEmpty() – Return true if the queue is empty, otherwise return false.
isFull() – Return true if the queue is full, otherwise return false.
(geeksforgeeks 10,2021)
Encapsulation
59
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Encapsulation is defined as the wrapping up of data under a single unit. It is the mechanism
that binds together code and the data it manipulates. Other way to think about encapsulation
is, it is a protective shield that prevents the data from being accessed by the code outside
this shield.
Technically in encapsulation, the variables or data of a class is hidden from any
other class and can be accessed only through any member function of own class
in which they are declared.
As in encapsulation, the data in a class is hidden from other classes using the
data hiding concept which is achieved by making the members or methods of
class as private and the class is exposed to the end user or the world without
providing any details behind implementation using the abstraction concept, so it
is also known as combination of data-hiding and abstraction.
Encapsulation can be achieved by: Declaring all the variables in the class as
private and writing public methods in the class to set and get the values of
variables.
60
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
In the above program the class EncapsulateDemo is encapsulated as the variables are
declared as private. The get methods like getAge() , getName() , getRoll() are set as public,
61
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
these methods are used to access these variables. The setter methods like setName(),
setAge(), setRoll() are also declared as public and are used to set the values of the variables.
Advantages of Encapsulation:
Data Hiding: The user will have no idea about the inner implementation of the
class. It will not be visible to the user that how the class is storing values in the
variables. He only knows that we are passing the values to a setter method and
variables are getting initialized with that value.
Increased Flexibility: We can make the variables of the class as read-only or
write-only depending on our requirement. If we wish to make the variables as
read-only then we have to omit the setter methods like setName(), setAge() etc.
from the above program or if we wish to make the variables as write-only then
we have to omit the get methods like getName(), getAge() etc. from the above
program
Reusability: Encapsulation also improves the re-usability and easy to change
with new requirements.
Testing code is easy: Encapsulated code is easy to test for unit testing.
(geeksforgeeks 4,2020)
62
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Applications of Queue
Direct applications
Indirect applications
auxiliary data structures for algorithms e.g in Breadth-First search queue is to store a
list of the nodes that need to be processed.
component of other data structures
63
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Testing
The above implementation can be validated as below:
Performance
(blog.miyozinc,2020)
Task 7: Implement the above scenario using the selected complex ADT.
Demonstrate how the implementation of an ADT/algorithm solves the above problem.
Critically evaluate the complexity of an implemented ADT/algorithm.
64
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Determine the different ways in which the efficiency of an algorithm can be measured,
illustrating your answer the algorithm which you have developed.
Stake Implementation
65
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Following are the screenshots of stack ADT
66
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
So now we have implemented the stack ADT, let’s input some values and check whether the
banquet halls are displayed from newest to oldest.
In Task 3 I briefly explained about Stake ADT, so now I’ll implement the stack ADT with
using an array data structure. For an example I ‘ll push 3 data elements in below array.
Push (80), push (92), and push (150)
01234
80 92 150
Stack Pointer=2
in stake ADT It will store the banquet hall id in LIFO (Last in first out) method,
In this stage newhall IDs are added to the front of the stack. As the result it allows us to
retrieve Banquet hallIDs from newest to oldest order method. Then we could maintain a set
67
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
of similar arrays(stacks) to keep other data about banquet halls. Such as hall name, locations
and seat capacity.
Critical Evaluation of the ADT Algorithm The algorithm given above solves the problem of
storing banquet hall ids from latest to oldest order. Whatever it has certain types of weakness.
Since this is an array implementation, the size of the stack must be defined in advance. Once
we defined then the size cannot change. Complexity of an algorithm is a measure of the
amount of time and/or space required by an algorithm for an input of a given size (n) which is
important to compare the performance of an algorithm. Therefore, we will do the same for
our implemented Stack ADT algorithm.
Note that instead of using array, the learner has used linked list to implement stack since
Linked list allocates the memory dynamically. As we saw from the codes above, the
operation which solves the problem is the display operation. So, let’s understand how the
display operation works by illustrating it. As we can see from illustration above when the
display operation is called it first displays the top element and then removes the top node by
making the successor of the top node (top. Next) the top node. Then it displays the top
element again and the process goes on till the top node is empty
Explain the different ways in which the efficiency of an algorithm can be measured,
illustrating your answer the algorithm which you have developed.
The efficiency of an algorithm is mainly defined by two factors i.e., space and time. A good
algorithm is one that is taking less time and less space, but this is not possible all the time.
There is a trade-off between time and space. If you want to reduce the time, then space might
increase. Similarly, if you want to reduce the space, then the time may increase. So, you have
to compromise with either space or time. Let's learn more about space and time complexity of
algorithms.
Space Complexity
Space Complexity of an algorithm denotes the total space used or needed by the algorithm for
its working, for various input sizes. For example:
vector<int> myVec(n);
for(int i = 0; i < n; i++)
cin >> myVec[i];
In the above example, we are creating a vector of size n. So the space complexity of the
above code is in the order of "n" i.e. if n will increase, the space requirement will also
increase accordingly.
68
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Even when you are creating a variable then you need some space for your algorithm to run.
All the space required for the algorithm is collectively called the Space Complexity of the
algorithm.
Time Complexity
The time complexity is the number of operations an algorithm performs to complete its task
with respect to input size (considering that each operation takes the same amount of time).
The algorithm that performs the task in the smallest number of operations is considered the
most efficient one.
The time taken by an algorithm also depends on the computing speed of the system that you
are using, but we ignore those external factors and we are only concerned on the number of
times a particular statement is being executed with respect to the input size. Let's say, for
executing one statement, the time taken is 1sec, then what is the time taken for executing n
statements, it will take n seconds.
(afteracademy,2019)
Task 8: Asymptotic analysis can be used to assess the effectiveness of an algorithm. How
to use the Asymptotic analysis for the scenario given in task 7? What sort of trade-offs
exists when you use a ADT for implementing programs? Describe the benefits of using
independent data structures for implementing programs.
Asymptotic Analysis
Asymptotic analysis of an algorithm refers to defining the mathematical foundation/framing
of its run-time performance. Using asymptotic analysis, we can very well conclude the best
case, average case, and worst-case scenario of an algorithm.
Asymptotic analysis is input bound i.e., if there's no input to the algorithm, it is concluded to
work in a constant time. Other than the "input" all other factors are considered constant.
Asymptotic analysis refers to computing the running time of any operation in mathematical
units of computation. For example, the running time of one operation is computed as f(n)
and may be for another operation it is computed as g(n2). This means the first operation
69
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
running time will increase linearly with the increase in n and the running time of the second
operation will increase exponentially when n increases. Similarly, the running time of both
operations will be nearly the same if n is significantly small.
Usually, the time required by an algorithm falls under three types −
Best Case − Minimum time required for program execution.
Average Case − Average time required for program execution.
Worst Case − Maximum time required for program execution.
(tutorialspoint,2020)
Θ Notation (theta)
Big O Notation
Ω Notation
Θ Notation (theta)
The Θ Notation is used to find the average bound of an algorithm i.e. it defines an upper
bound and a lower bound, and your algorithm will lie in between these levels. So, if a
function is g(n), then the theta representation is shown as Θ(g(n)) and the relation is shown
as:
The above expression can be read as theta of g(n) is defined as set of all the functions f(n) for
which there exists some positive constants c1, c2, and n0 such that c1*g(n) is less than or
equal to f(n) and f(n) is less than or equal to c2*g(n) for all n that is greater than or equal to
n0.
For example:
if f(n) = 2n² + 3n + 1
and g(n) = n²
then for c1 = 2, c2 = 6, and n0 = 1, we can say that f(n) = Θ(n²)
70
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Big O Notation
The Big O notation defines the upper bound of any algorithm i.e. you algorithm can't take
more time than this time. In other words, we can say that the big O notation denotes the
maximum time taken by an algorithm or the worst-case time complexity of an algorithm. So,
big O notation is the most used notation for the time complexity of an algorithm. So, if a
function is g(n), then the big O representation of g(n) is shown as O(g(n)) and the relation is
shown as:
if f(n) = 2n² + 3n + 1
and g(n) = n²
then for c = 6 and n0 = 1, we can say that f(n) = O(n²)
71
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
.
Ω Notation
The Ω notation denotes the lower bound of an algorithm i.e. the time taken by the algorithm
can't be lower than this. In other words, this is the fastest time in which the algorithm will
return a result. Its the time taken by the algorithm when provided with its best-case input. So,
if a function is g(n), then the omega representation is shown as Ω(g(n)) and the relation is
shown as:
if f(n) = 2n² + 3n + 1
and g(n) = n²
then for c = 2 and n0 = 1, we can say that f(n) = Ω(n²)
(afteracademy,2019)
Using the Asymptotic Analysis for the problem mentioned earlier for example, let’s use the
operations in the Stack ADT we implemented to solve a problem in the previous topic. The
operations which will be analyzing are the push, pop and display operations
Given two algorithms for a task, how do we find out which one is better?
One naive way of doing this is – implement both the algorithms and run the two programs
on your computer for different inputs and see which one takes less time. There are many
problems with this approach for analysis of algorithms.
72
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
1) It might be possible that for some inputs, first algorithm performs better than the second.
And for some inputs second performs better.
2) It might also be possible that for some inputs, first algorithm performs better on one
machine and the second works better on other machine for some other inputs.
Asymptotic Analysis is the big idea that handles above issues in analyzing algorithms. In
Asymptotic Analysis, we evaluate the performance of an algorithm in terms of input size
(we don’t measure the actual running time). We calculate, how the time (or space) taken by
an algorithm increases with the input size.
For example, let us consider the search problem (searching a given item) in a sorted array.
One way to search is Linear Search (order of growth is linear) and the other way is Binary
Search (order of growth is logarithmic). To understand how Asymptotic Analysis solves the
above-mentioned problems in analyzing algorithms, let us say we run the Linear Search on
a fast computer A and Binary Search on a slow computer B and we pick the constant values
for the two computers so that it tells us exactly how long it takes for the given machine to
perform the search in seconds. Let’s say the constant for A is 0.2 and the constant for B is
1000 which means that A is 5000 times more powerful than B. For small values of input
array size n, the fast computer may take less time. But, after a certain value of input array
size, the Binary Search will definitely start taking less time compared to the Linear Search
even though the Binary Search is being run on a slow machine. The reason is the order of
growth of Binary Search with respect to input size is logarithmic while the order of growth
of Linear Search is linear. So, the machine dependent constants can always be ignored after
a certain value of input size .
It is a well-established fact that merge sort runs faster than insertion sort. Using asymptotic
analysis we can prove that merge sort runs in O(nlogn) time and insertion sort takes O(n^2).
It is obvious because merge sort uses a divide-and-conquer approach by recursively solving
the problems where as insertion sort follows an incremental approach.
If we scrutinize the time complexity analysis even further, we’ll get to know that insertion
sort isn’t that bad enough. Surprisingly, insertion sort beats merge sort on smaller input size.
This is because there are few constants which we ignore while deducing the time complexity.
On larger input sizes of the order 10^4 this doesn’t influence the behavior of our function.
But when input sizes fall below, say less than 40, then the constants in the equation dominate
the input size ‘n’.
73
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
So far, so good. But I wasn’t satisfied with such mathematical analysis. As a computer
science undergrad we must believe in writing code. I’ve written a C program to get a feel of
how the algorithms compete against each other for various input sizes. And also, why such
rigorous mathematical analysis is done on establishing running time complexities of these
sorting algorithms.
74
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
75
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
76
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
77
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
I have compared the running times of the following algorithms:
Insertion sort: The traditional algorithm with no modifications/optimisation. It
performs very well for smaller input sizes. And yes, it does beat merge sort
Merge sort: Follows the divide-and-conquer approach. For input sizes of the
order 10^5 this algorithm is of the right choice. It renders insertion sort
impractical for such large input sizes.
Combined version of insertion sort and merge sort: I have tweaked the logic
of merge sort a little bit to achieve a considerably better running time for smaller
78
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
input sizes. As we know, merge sort splits its input into two halves until it is
trivial enough to sort the elements. But here, when the input size falls below a
threshold such as ’n’ < 40 then this hybrid algorithm makes a call to traditional
insertion sort procedure. From the fact that insertion sort runs faster on smaller
inputs and merge sort runs faster on larger inputs, this algorithm makes best use
both the worlds.
Quick sort: I have not implemented this procedure. This is the library function
qsort() which is available in . I have considered this algorithm in order to know
the significance of implementation. It requires a great deal of programming
expertise to minimize the number of steps and make at most use of the
underlying language primitives to implement an algorithm in the best way
possible. This is the main reason why it is recommended to use library functions.
They are written to handle anything and everything. They optimize to the
maximum extent possible. And before I forget, from my analysis qsort() runs
blazingly fast on virtually any input size!
The Analysis:
Input: The user has to supply the number of times he/she wants to test the
algorithm corresponding to number of test cases. For each test case the user must
enter two space separated integers denoting the input size ’n’ and the
‘num_of_times’ denoting the number of times he/she wants to run the analysis
and take average. (Clarification: If ‘num_of_times’ is 10 then each of the
algorithm specified above runs 10 times and the average is taken. This is done
because the input array is generated randomly corresponding to the input size
which you specify. The input array could be all sorted. Our it could correspond
to the worst case .i.e. descending order. In order to avoid running times of such
input arrays. The algorithm is run ‘num_of_times‘ and the average is taken.)
clock() routine and CLOCKS_PER_SEC macro from is used to measure the
time taken.
Compilation: I have written the above code in Linux environment
(Ubuntu 16.04 LTS). Copy the code snippet above. Compile it using gcc, key in the inputs
as specified and admire the power of sorting algorithms!
Results: As you can see for small input sizes, insertion sort beats merge sort by 2 * 10^-6
sec. But this difference in time is not so significant. On the other hand, the hybrid
algorithm and qsort() library function, both perform as good as insertion sort.
The input size is now increased by approximately 100 times to n = 1000 from n = 30. The
difference is now tangible. Merge sort runs 10 times faster than insertion sort. There is again
a tie between the performance of the hybrid algorithm and the qsort() routine. This suggests
79
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
that the qsort() is implemented in a way which is more or less similar to our hybrid
algorithm i.e., switching between different algorithms to make the best out of them.
Finally, the input size is increased to 10^5 (1 Lakh!) which is most probably the ideal size
used in practical scenario’s. Compared to the previous input n = 1000 where merge sort
beat insertion sort by running 10 times faster, here the difference is even more significant.
Merge sort beats insertion sort by 100 times!
The hybrid algorithm which we have written in fact does out perform the traditional merge
sort by running 0.01 sec faster. And lastly, qsort() the library function, finally proves us that
implementation also plays a crucial role while measuring the running times meticulously by
running 3 milliseconds faster!
(geeksforgeeks 9,2020)
Abstract data types offer several advantages over concrete data types:
80
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
(course.ccs.neu.edu,2020)
When specifying an ADT, the first thing we should know is that any problem can be solved
with the right ADT. Apart from that, we may face some situation in which we might have to
sacrifice something to improve something. And this is called the trade-off. Simply, trade-off
means a balance achieved between two desirable but incompatible features; a compromise.
So, when we are specifying an ADT, we might have to face some trade-off. And some of the
common trade-of is as follow
Space-time Trade-Off
we will discuss Time-Space Trade-Off in Algorithms. A tradeoff is a situation where one
thing increases and another thing decreases. It is a way to solve a problem in:
Either in less time and by using more space, or
In very little space by spending a long amount of time.
The best Algorithm is that which helps to solve a problem that requires less space in
memory and also takes less time to generate the output. But in general, it is not always
possible to achieve both of these conditions at the same time. The most common condition
is an algorithm using a lookup table. This means that the answers to some questions for
every possible value can be written down. One way of solving this problem is to write
down the entire lookup table, which will let you find answers very quickly but will use a
lot of space. Another way is to calculate the answers without writing down anything, which
uses very little space, but might take a long time. Therefore, the more time-efficient
algorithms you have, that would be less space-efficient.
Types of Space-Time Trade-off
Re-Rendering or Stored images : In this case, storing only the source and rendering it as
an image would take more space but less time i.e., storing an image in the cache is faster
than re-rendering but requires more space in memory.
Smaller code or Loop Unrolling: Smaller code occupies less space in memory but it
requires high computation time that is required for jumping back to the beginning of the
loop at the end of each iteration. Loop unrolling can optimize execution speed at the cost of
increased binary size. It occupies more space in memory but requires less computation
time.
81
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Lookup tables or Recalculation : In a lookup table, an implementation can include the
entire table which reduces computing time but increases the amount of memory needed. It
can recalculate i.e., compute table entries as needed, increasing computing time but
reducing memory requirements.
(geeksforgeeks.,2021)
82
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Refference list
83
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
13. (geeksforgeeks 9,2020, viewed on 10th January
2020<https://www.geeksforgeeks.org/asymptotic-analysis-comparison-sorting-
algorithms/>)
14. (course.ccs.neu.edu,2020, viewed on 10th January
2020<https://course.ccs.neu.edu/cs5010f17/InterfacesClasses2/advantagesADT1.html
?>)
15. (2braces,2021, viewed on 16th February 2021<https://www.2braces.com/data-
structures/selection-sort>)
16. (2braces 1,2021, viewed on 16th February 2021<https://www.2braces.com/data-
structures/insertion-sort>)
17. (geeksforgeeks 10,2021, viewed on 16th February 2021
<https://www.geeksforgeeks.org/abstract-data-types/>)
18. (blog.miyozinc,2020, viewed on 16th February
2021<https://blog.miyozinc.com/algorithms/queue-adt-implementation/>)
19. (afteracademy,2019, viewed on 16th February
2021<https://afteracademy.com/blog/time-and-space-complexity-analysis-of-
algorithm#:~:text=Algorithm%20Efficiency&text=A%20good%20algorithm%20is
%20one,then%20the%20time%20may%20increase.>)
84
A.M.BELICKS
COL/E-008348
UNIT – 19 DS