0% found this document useful (0 votes)
11 views84 pages

Unit 19 Dsa Assignment

The document outlines the internal verification process for assessment decisions related to BTEC Higher Nationals, specifically focusing on Unit 19: Data Structures and Algorithms. It includes guidelines for assignment submission, assessment criteria, and feedback mechanisms, as well as a detailed assignment brief with tasks related to data structures, algorithms, and their applications in a hotel reservation scenario. Additionally, it emphasizes the importance of proper referencing, plagiarism policies, and the responsibilities of students in managing their submissions.

Uploaded by

belicksbell
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)
11 views84 pages

Unit 19 Dsa Assignment

The document outlines the internal verification process for assessment decisions related to BTEC Higher Nationals, specifically focusing on Unit 19: Data Structures and Algorithms. It includes guidelines for assignment submission, assessment criteria, and feedback mechanisms, as well as a detailed assignment brief with tasks related to data structures, algorithms, and their applications in a hotel reservation scenario. Additionally, it emphasizes the importance of proper referencing, plagiarism policies, and the responsibilities of students in managing their submissions.

Uploaded by

belicksbell
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/ 84

Higher Nationals

Internal verification of assessment decisions – BTEC (RQF)

INTERNAL VERIFICATION – ASSESSMENT DECISIONS


Programme title

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.

INTERNAL VERIFIER CHECKLIST

Do the assessment criteria awarded match


those shown in the assignment brief? Y/N

Is the Pass/Merit/Distinction grade awarded


justified by the assessor’s comments on the Y/N
student work?

Has the work been assessed


Y/N
accurately?

Is the feedback to the student:


Give details:
• Constructive?
• Linked to relevant assessment criteria? Y/N
Y/N
• Identifying opportunities for improved Y/N
performance?
Y/N
• Agreeing actions?

Does the assessment decision need


Y/N
amending?

Assessor signature Date

Internal Verifier signature Date


Programme Leader signature (if required)
Date
Confirm action completed
Remedial action taken
Give details:

Assessor signature Date


Internal Verifier
Date
signature

Programme Leader
Date
signature (if required)
Higher Nationals - Summative Assignment Feedback Form

Student Name/ID

Unit Title Unit 19: Data Structures and Algorithms

Assignment Number 1 Assessor

Date Received 1st


Submission Date
submission

Date Received 2nd


Re-submission Date
submission
Assessor Feedback:
LO1 Demonstrate a range of interpersonal and transferable communication skills to a target audience
Pass, Merit & Distinction P1 P2 M1 M2 D1
Descripts

LO2 Apply critical reasoning and thinking to a range of problem-solving scenarios


Pass, Merit & Distinction P3 M3 D2
Descripts

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

Grade: Assessor Signature: Date:

Resubmission Feedback:

Grade: Assessor Signature: Date:

Internal Verifier’s Comments:

Signature & 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.

Assignment Feedback

Formative Feedback: Assessor to Student

Action Plan

Summative feedback
Feedback: Student to Assessor

Assessor signature Date

Student signature Date

Pearson Higher Nationals in


Computing
Unit 19: Data Structures & Algorithms
Assignment 01
General Guidelines

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).

Word Processing Rules

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.

1. I know that plagiarism is a punishable offence because it constitutes theft.


2. I understand the plagiarism and copying policy of Edexcel UK.
3. I know what the consequences will be if I plagiarise or copy another’s work in any of the
assignments for this program.
4. I declare therefore that all work presented by me for every aspect of my program, will be my
own, and where I have made use of another’s work, I will attribute the source in the correct
way.
5. I acknowledge that the attachment of this document signed or not, constitutes a binding
agreement between myself and Edexcel UK.
6. I understand that my assignment will not be considered as submitted if this document is not
attached to the assignment.

[email protected] 17/02/2021
Student’s Signature: Date:
(Provide E-mail ID) (Provide Submission Date)
Higher National Diploma in Business

Assignment Brief

Student Name /ID Number A.M.Belicks / COL/E-008348


Unit Number and Title Unit 19: Data Structures and Algorithms
Academic Year 2019/20
Unit Tutor
Assignment Title Specification, Implementation, and Assessment of Data Structures for a
sample scenario.
Issue Date
Submission Date
IV Name & Date

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.

Unit Learning Outcomes:

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.

If customer requested a date change or a location change or a change in number of guests, he


or she is placed back in the waiting list and must wait again for another reservation.
We will assume that each banquet hall, once accepted, will be occupied by a reservation ID.
Insert banquet hall details, reservation details and customer details through the keyboard.
The reservation process should remove a banquet hall on a given date from the queue if the
customer “accepts” the reservation. If the customer rejects or changes the reservation delete
the customer reservation, insert it to the back of the queue and compare next customer
reservation and repeat. This process repeats until all customers complete their reservations.
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?

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

Grading Criteria Achieved Feedback

LO1. Examine abstract data types, concrete data structures


and algorithms.

P1 Create a design specification for data structures explaining


the valid operations that can be carried out on the structures.

P2 Determine the operations of a memory stack and how it is


used to implement function calls in a computer.

M1 Illustrate, with an example, a concrete data structure for


a First In First out (FIFO) queue.

M2 Compare the performance of two sorting


algorithms.
D1 Analyse the operation, using illustrations, of two network
shortest path algorithms, providing an example of each.

15
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
LO2. Specify abstract data types and algorithms in a
formal notation.

P3 Using an imperative definition, specify the abstract data


type for a software stack.

M3 Examine the advantages of encapsulation and


information hiding when using an ADT.
D2 Discuss the view that imperative ADTs are a basis for
object orientation and, with justification, state whether you
agree.

LO3. Implement complex data structures and algorithms.

P4 Implement a complex ADT and algorithm in an executable


programming language to solve a well-defined problem.

P5 Implement error handling and report test results.

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.

LO4. Assess the effectiveness of data structures and


algorithms.
P6 Discuss how asymptotic analysis can be used to assess the
effectiveness of an algorithm.
P7 Determine two ways in which the efficiency of an
algorithm can be measured, illustrating your answer with an
example.
M5 Interpret what a trade-off is when specifying an ADT
using an example to support your answer.
D4 Evaluate three benefits of using implementation
independent data structures.

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.

(Rajeev Singh, 2018 )

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:

- Add an element to queue called as enqueue


- Remove an element from queue called as Dequeue

Valid Operations of the queue Data Structure

enqueue ()

This function defines the operation for adding an element into queue

dequeue ()

This function defines the operation for removing an element from queue.

init () / (is full, is empty)

This function is used for initializing the queue.

Search

Searching is an operation or a technique that helps finds the place of a given element or value
in the list.

Front

Front is used to get the front data item from a queue.

Rear

Rear is used to get the last item from a queue


21
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Queue data structure functions, based system requirements

1. When customer make a reservation and respond it within a day

Enqueue

A queue always maintains two pointers, there are front and rear, steps for the enqueue
reservation in the queue

Step 1 – check reservation queue is full or not

Step 2 – if it is full, produce an overflow error

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.

Step 5 – Successfully reservation Placed

Example –

Rear Waiting list Front


reservation

Reservation 4 Reservation 3 Reservation 2 Reservation 1

After getting a confirmation, particular reservation should remove in the waiting list. And add
to the confirm reservation.

After customer responded:

Reservation 4 Confirmed
Rear Front
reservation

Reservation 3 Reservation 2 Reservation 1

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.

Rear Confirmed Front


Reservation

Reservation 4 Reservation 3 Reservation 2 Reservation 1

2. If the customer booked the temporary reservation but not respond within a day.

Rear Waiting list Front


reservation

Reservation 4 Reservation 3 Reservation 2 Reservation 1

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

Reservation 3 Reservation 2 Reservation 1

Remove

Reservation 4

Add

Rear Waiting list Front


reservation

Reservation 4 Reservation 3 Reservation 2 Reservation 1

4. If customer accept the reservation without any changes

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

Reservation 3 Reservation 2 Reservation 1


Reservation 4

Remove
25
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Add

Rear Confirmed Front


reservation

Reservation 4 Reservation 3 Reservation 2 Reservation 1

Banquet list

Rear Front
Available Banquet
halls

Banquet 3 Banquet 2 Banquet 1

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 1 – Check Hotel Reservation queue is full or not

Step 2 – If Hotel Reservation queue is empty then produce underflow error

Step 3 - If Hotel Reservation queue is not empty, access hotel reservation from front pointing

Step 4 - Increment front pointer to point next available reservation.

Step 5 – Return as successful delete or function remove

Example for Dequeue

 If customer not responding hotel reservation within a day


 If customer change their requirement about reservation
 if customer reject the reservation

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

Reservation 4 Reservation 3 Reservation 2 Reservation 1

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

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

Implementation of queue data structure in system

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.

Reservation Queue Code

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

Hotel Reservation System

Test plan ID 01

Brief introduction This system is named as Hotel Reservation System, and it is a


about the system software which manages information about the Customers and
the recipients.

Brief introduction This document defines the plan for testing the Hotel
about the testing Reservation System, and this document supports the following
objectives objectives:

1. Testing the features of the system


2. List the recommended test requirements
3. Describing the recommended test strategies
4. List the deliverables elements of the test activities

Test items(modules) Functions of the system

Features to be tested Confirm the reservation, Reject Confirm the reservation,


change the details of reservation , confirmed reservation, reject
reservation

Test environment At home,

Test Approach Black Box

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.

Staffing and Training Not essential


needs

Schedule 2nd December 2020, 1.00PM to 6.00PM

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 ID: 01 Test designed date: 2nd December


2020

Test executed by: A.M.Belicks

Description: Confirm the Temporary Test execution date :2nd December


reservation 202

Test execution time: 3.30PM –


3.40PM

Test Input Expected result Actual result Status


(pass/fail)

Temp_Reservation_ID Customer Details. Customer Details. Pass


Search Button Reservation_id Reservation_id add
add waiting list. waiting list. Queue
Queue confirmed. confirmed. Available
Available banquet banquet hall deleted
hall deleted

Project Name: Hotel Reservation System

Test Case

Test unit: Temporary Reservation Not Confirmed Test designed by: A.M.Belicks

Test case ID: 02 Test designed date: 24th June 2019

Test executed by: - A.M.Belicks

Description: Not confirming Temporary Test execution date: 2nd December


32
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Reservation 2020

Test execution time: 3.40PM –


3.50PM

Test Input Expected Actual result Status


result (pass/fail)

Temp_Reservation_ID Search Customer Customer Details. Pass


Button Details. Reservation_id add
Reservation_id waiting list.
add waiting
list.

Project Name: Hotel Reservation System

Test Case

Test unit: Change Reservation Details. Test designed by: A.M.Belicks

Test case ID: 03 Test designed date: 2nd December


2020

Test executed by: A.M.Belicks

Description: Customer change the hotel Test execution date: 2nd December
Reservation Details 2020

Test execution time: 3.50PM –


4.00PM

Test input Expected result Actual result Status


(pass/fail)

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

Project Name: Hotel Reservation System

Test Case

Test unit: Customer Accept Test designed by: A.M.Belicks

Test case ID : 04 Test designed date: 2nd December


2020

Test executed by: A.M.Belicks

Description: Customer accept the Test execution date: 2nd December


Reservation 2020

Test execution time: 4.10PM –


4.20PM

Test input Expected result Actual result Status


(pass/fail)

Confirmed Remove waiting list Remove waiting list Pass


and available banquet and available
hall. banquet hall.

34
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Project Name: Hotel Reservation System

Test Case

Test unit: Rejecting the Customer Test designed by: A.M.Belicks

Test case ID: 05 Test designed date: 2nd December


2020

Test executed by: A.M.Belicks

Description: Rejecting the Customer Test execution date: 2nd December


2020

Test execution time: 4.20PM –


4.30PM

Test data Expected result Actual result Status


(pass/fail)

Rejected Remove Remove waiting list Pass


waiting list and and available banquet
available hall.
banquet hall.

Project Name: Hotel Reservation System

Test Case

Test unit: After Reservation Test designed by: A.M.Belicks

Test case ID: 06 Test designed date: 2nd December


2020

Test executed by: A.M.Belicks

Description: after hotel reservation Test execution date: 2nd December


2020

35
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Test execution time: 4.30PM –
4.40PM

Test data Expected result Actual result Status


(pass/fail)

Confirmed Customer Details Customer Details Pass


add Database add Database

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

//store the content of specified memory address

36
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
//into SP; i.e, at top of stack

SP <-- (memory address)

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:

//transfer the content of SP (i.e, at top most data)

//into specified memory location

(memory address) <-- SP

//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.

Sorting Sort / Selecting Sort Algorithms

A Sorting Algorithm is used to rearrange a given array or list elements according to a


comparison operator on the elements. The comparison operator is used to decide the new
order of element in the respective data structure.

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;

// One by one move boundary of unsorted subarray


for (int i = 0; i < n-1; i++)
{
// Find the minimum element in unsorted array
int min_idx = i;
for (int j = i+1; j < n; j++)
if (arr[j] < arr[min_idx])
min_idx = j;

// Swap the found minimum element with the first


// element
int temp = arr[min_idx];
arr[min_idx] = arr[i];
arr[i] = temp;
}
}

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();
}

// Driver code to test above


public static void main(String args[])
{
SelectionSort ob = new SelectionSort();
int arr[] = {64,25,12,22,11};
ob.sort(arr);
System.out.println("Sorted array");
ob.printArray(arr);
}
}

(geeksforgeeks 2,2020)

Advantages - Selection Sort

 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.

Disadvantages - Selection Sort

 Running time of Selection sort algorithm is very poor of 0 (n2).


 Insertion sort algorithm is far better than selection sort algorithm
(2braces,2021)

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;

/* Move elements of arr[0..i-1], that are


greater than key, to one position ahead
of their current position */

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;
}
}

/* A utility function to print array of size n*/


static void printArray(int arr[])
{
int n = arr.length;
for (int i = 0; i < n; ++i)
System.out.print(arr[i] + " ");

System.out.println();
}

// Driver method
public static void main(String args[])
{
int arr[] = { 12, 11, 13, 5, 6 };

InsertionSort ob = new InsertionSort();


ob.sort(arr);

printArray(arr);
}

(geeksforgeeks 3,2020)

Advantages - Insertion Sort

 Insertion sort algorithm requires less memory space.


 Insertion sort algorithm is easy to implement and efficient to use on small amount of
data.
 Insertion sort algorithm is more efficient when few or more elements are already
sorted.

Disadvantages - Insertion Sort

 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

Difference Between Insertion Sort and Selection 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.

3) While sptSet doesn‟t includes all vertices

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.

Let us understand with the following example:

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).

Java Coding for implementation

// A Java program for Dijkstra's single source shortest path algorithm.


// The program is for adjacency matrix representation of the graph
import java.util.*;
import java.lang.*;
48
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
import java.io.*;

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;

for (int v = 0; v < V; v++)


if (sptSet[v] == false && dist[v] <= min) {
min = dist[v];
min_index = v;
}

return min_index;
}

// A utility function to print the constructed distance array


void printSolution(int dist[])
{
System.out.println("Vertex \t\t Distance from Source");
for (int i = 0; i < V; i++)
System.out.println(i + " \t\t " + dist[i]);
}

// Function that implements Dijkstra's single source shortest path


// algorithm for a graph represented using adjacency matrix
// representation
void dijkstra(int graph[][], int src)
{
int dist[] = new int[V]; // The output array. dist[i] will hold
// the shortest distance from src to i

// sptSet[i] will true if vertex i is included in shortest


// path tree or shortest distance from src to i is finalized
Boolean sptSet[] = new Boolean[V];

// Initialize all distances as INFINITE and stpSet[] as false


for (int i = 0; i < V; i++) {
dist[i] = Integer.MAX_VALUE;
sptSet[i] = false;
}

// Distance of source vertex from itself is always 0


dist[src] = 0;

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);

// Mark the picked vertex as processed


sptSet[u] = true;

// Update dist value of the adjacent vertices of the


// picked vertex.
for (int v = 0; v < V; v++)

// Update dist[v] only if is not in sptSet, there is an


// edge from u to v, and total weight of path from src to
// v through u is smaller than current value of dist[v]
if (!sptSet[v] && graph[u][v] != 0 && dist[u] != Integer.MAX_VALUE &&
dist[u] + graph[u][v] < dist[v])
dist[v] = dist[u] + graph[u][v];
}

// print the constructed distance array


printSolution(dist);
}

// 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.

INITIALIZE - SINGLE - SOURCE (G, s)


1. for each vertex v ∈ V [G]
2. do d [v] ← ∞
3. π [v] ← NIL
4. d [s] ← 0

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.

(a) Because v. d > u. d + w (u, v) prior to relaxation, the value of v. d decreases

(b) Here, v. d < u. d + w (u, v) before relaxing the edge, and so the relaxation step leaves
v. d unchanged.

The subsequent code performs a relaxation step on edge (u, v)

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.

Abstract data type (ADT)


abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a set of
value and a set of operations.

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.

The program to access variables of the class EncapsulateDemo is shown below:

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

 the waiting list, bureaucracy


 access to shared resources (e.g. printer)
 implementing the cache (evicting first cached element)
 OS multiprogramming

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

Linked List-based stack

Queue ADT implementation with Linked List is straightforward by maintaining pointers


to both first and last element registered to the list.

Here is Java implementation for queue ADT.

63
A.M.BELICKS
COL/E-008348
UNIT – 19 DS
Testing
The above implementation can be validated as below:

Performance

For n be the number of elements in the Queue

The space used is O(n)

Each operation runs in time O(1)

(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)

There are three types of asymptotic notations

 Θ 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:

Θ(g(n)) = { f(n): there exist positive constants c1, c2 and n0


such that 0 ≤ c1g(n) ≤ f(n) ≤ c2g(n) for all n ≥ n0 }

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:

O(g(n)) = { f(n): there exist positive constants c and n0


such that 0 ≤ f(n) ≤ cg(n) for all n ≥ n0 }
The above expression can be read as Big O of g(n) is defined as a set of functions f(n) for
which there exist some constants c and n0 such that f(n) is greater than or equal to 0 and f(n)
is smaller than or equal to c*g(n) for all n greater than or equal to n0.

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:

Ω(g(n)) = { f(n): there exist positive constants c and n0


such that 0 ≤ cg(n) ≤ f(n) for all n ≥ n0 }
The above expression can be read as omega of g(n) is defined as set of all the functions f(n)
for which there exist some constants c and n0 such that c*g(n) is less than or equal to f(n), for
all n greater than or equal to n0.

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 .

Does Asymptotic Analysis always work?


Asymptotic Analysis is not perfect, but that’s the best way available for analyzing algorithms.
For example, say there are two sorting algorithms that take 1000nLogn and 2nLogn time
respectively on a machine. Both of these algorithms are asymptotically same (order of growth
is nLogn). So, With Asymptotic Analysis, we can’t judge which one is better as we ignore
constants in Asymptotic Analysis.
Also, in Asymptotic analysis, we always talk about input sizes larger than a constant value. It
might be possible that those large inputs are never given to your software and an algorithm
which is asymptotically slower, always performs better for your particular situation. So, you
may end up choosing an algorithm that is Asymptotically slower but faster for your software.
(geeksforgeeks 6,2020)

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)

Advantages of Abstract Data Types

Abstract data types offer several advantages over concrete data types:

 Representation Independence: Most of the program becomes independent of the


abstract data type's representation, so that representation can be improved without
breaking the entire program.
 Modularity: With representation independence, the different parts of a program
become less dependent on other parts and on how those other parts are implemented.
 Interchangeability of Parts: Different implementations of an abstract data type may
have different performance characteristics. With abstract data types, it becomes easier
for each part of a program to use an implementation of its data types that will be more
efficient for that particular part of the program.

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

 Compressed or Uncompressed data


 Re Rendering or Stored images
 Smaller code or loop unrolling
 Lookup tables or Recalculation
Compressed or Uncompressed data : A space-time trade-off can be applied to the problem
of data storage. If data stored is uncompressed, it takes more space but less time. But if the
data is stored compressed, it takes less space but more time to run the decompression
algorithm. There are many instances where it is possible to directly work with compressed
data. In that case of compressed bitmap indices, where it is faster to work with compression
than without compression.

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

1. (Rajeev Singh, 2018 , viewed on 6th November 2020


<https://www.callicoder.com/java-queue/>)
2. (geeksforgeeks,2019, viewed on 6th November 2020<
https://www.geeksforgeeks.org/introduction-of-stack-based-cpu-organization/>)
3. (geeksforgeeks 2,2020, viewed on 2nd January 2021
<https://www.geeksforgeeks.org/sorting-algorithms/>)
4. (geeksforgeeks 3,2020, viewed on 2 nd December
2020<https://www.geeksforgeeks.org/insertion-sort/>)
5. (pediaa,2020, viewed on 2nd January 2021<https://pediaa.com/what-is-the-
difference-between-insertion-sort-and-selection-sort/#:~:text=The%20main
%20difference%20between%20insertion,the%20element%20in%20the%20correct>)
6. (geeksforgeeks 3,2020, viewed on 4 th January
2021<https://www.geeksforgeeks.org/dijkstras-shortest-path-algorithm-greedy-algo-
7/>)
7. (javatpoint,2020), viewed on 4th January2021
2020https://www.javatpoint.com/relaxation

8. (data-flair,2020, viewed on 4th January 2021<https://data-flair.training/blogs/abstract-


data-type-adt/>)
9. (geeksforgeeks 4,2020, viewed on 4th January
2021<https://www.geeksforgeeks.org/encapsulation-in-java/#:~:text=Encapsulation
%20is%20defined%20as%20the,the%20code%20outside%20this%20shield.>)
10. (btechsmartclass,2020, viewed on 4th January
2020<http://www.btechsmartclass.com/data_structures/stack-adt.html>)
11. (tutorialspoint,2020, viewed on 5th January 2021,
<https://www.tutorialspoint.com/data_structures_algorithms/asymptotic_analysis.htm
#:~:text=Asymptotic%20analysis%20is%20input%20bound,in%20mathematical
%20units%20of%20computation.>)
12. (geeksforgeeks 6,2020, viewed on 5th January
2021<https://www.geeksforgeeks.org/analysis-of-algorithms-set-1-asymptotic-
analysis/>)

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.>)

20. (geeksforgeeks.,2021,viewed on 17 th February


2021<https://www.geeksforgeeks.org/time-space-trade-off-in-algorithms/>)

84
A.M.BELICKS
COL/E-008348
UNIT – 19 DS

You might also like