You are on page 1of 26

ASSIGNMENT 2 BRIEF

Qualification BTEC Level 5 HND Diploma in Business

Unit number Unit 19: Data Structures and Algorithms

Assignment title Implement and assess specific DSA

Academic Year

Unit Tutor Ho Hai Van

Issue date Submission date

IV name and date

Submission Format:

Format: The submission is in the form of an individual written report. This should be written in a
concise, formal business style using single spacing and font size 12. You are required to make
use of headings, paragraphs and subsections as appropriate, and all work must be supported
with research and referenced using the Harvard referencing system. Please also provide a
bibliography using the Harvard referencing system.
Submission Students are compulsory to submit the assignment in due date and in a way requested by
the Tutors. The form of submission will be a soft copy in PDF posted on corresponding
course of http://cms.greenwich.edu.vn/ Project also needs to be submitted in zip format.
Note: The Assignment must be your own work, and not copied by or from another student or from
books etc. If you use ideas, quotes or data (such as diagrams) from books, journals or other sources, you
must reference your sources, using the Harvard style. Make sure that you know how to reference
properly, and that understand the guidelines on plagiarism. If you do not, you definitely get fail

Assignment Brief and Guidance:


Scenario: Continued from Assignment 1.

Tasks
For the middleware that is currently developing, one part of the provision interface is how message can be
transferred and processed through layers. For transport, normally a buffer of queue messages is implemented and
for processing, the systems requires a stack of messages.

Page 1
The team now has to develop these kind of collections for the system. They should design ADT / algorithms for these
2 structures and implement a demo version with message is a string of maximum 250 characters. The demo

Page 2
Table of Contents
ASSIGNMENT 2 BRIEF ......................................................................................................................................... 1
Assignment 2 ..................................................................................................................................................... 4
P4 Implement a complex ADT and algorithm in an executable programming language to solve a well
defined problem. ................................................................................................................................................ 4
P5 Implement error handling and report test results. ..................................................................................... 11
P6 Discuss how asymptotic analysis can be used to assess the effectiveness of an algorithm. ...................... 13
1. Analysis of Algorithms: ............................................................................................................................. 13

2. The Execution Time of Algorithms: .......................................................................................................... 14

3. General Rules for Estimation:................................................................................................................... 15

4. Algorithm Growth Rates: .......................................................................................................................... 16

5. Growth-Rate Functions – Example 1: ....................................................................................................... 17

6. Example using stack: ................................................................................................................................ 18

P7 Determine two ways in which the efficiency of an algorithm can be measured, illustrating your answer
with an example. .............................................................................................................................................. 20
1. Algorithmic Performance: ........................................................................................................................ 20

2. Analysis of Algorithms: ............................................................................................................................. 20

3. Growth Rates: ........................................................................................................................................... 21

4. Order of Magnitude Analysis and Big O Notation: ................................................................................... 22

5. Definition of the Order of an Algorithm: .................................................................................................. 23

References ....................................................................................................................................................... 26

Page 3
Assignment 2
P4 Implement a complex ADT and algorithm in an executable programming language to solve a well
defined problem.
I will present an algorithm - Convert 10 to binary
Linkedlist Implementation of Stack

In mathematics and digital electronics, a binary number is a number expressed in the base-2 numeral
system or binary numeral system, which uses only two symbols: typically "0" (zero) and "1" (one).
This can be executed by using a stack.

Page 4
Page 5
Implement of convert 10 to a
binary public class ArrayStackImp {
public static void main(String[] args){
decToBin(10);
}
public static void decToBin(int k){
ArrayStack s = new ArrayStack();
System.out.println(k + " in binary system is: ");
while (k>0) {
s.push(k%2);
k = k/2;
}
while(!s.isEmpty()){
System.out.print(s.pop());
}
System.out.println("");
}
}
class ArrayStack{
protected Object[] a;
int top, max;

public ArrayStack(int
max){ this.max = max;
a = new Object[max];
top=-1;
}
public ArrayStack(){
this(50);
}
public boolean isEmpty(){
return top==-1;
}
public boolean isFull(){
return top == max-1;
}
public void clear(){
top=-1;
}
public boolean grow(){ int
max1 = max + max/2; Object[] a1

Page 6
= new Object[max1]; if
(a1==null){ //cannot create new array
return false;
}
for (int i = 0; i < top; i++){ a1[i]
= a[i]; //copy values from a to a1
}
a = a1; //now a is a1
max = max1; //now max is max1
return true;
}
public void push(Object x){
if(isFull() && !grow()) return;
a[++top] = x;
}
public Object top() throws EmptyStackException{
if(isEmpty()) throw new EmptyStackException();
return (a[top]);
}
public Object pop() throws
EmptyStackException{ if(isEmpty()) throw new
EmptyStackException(); Object x = a[top];
top--; return x;
}
}
Explain code

• Create a stack and set conditions. After that, if int k>o Put it into the stack

Page 7
• Object: contain data as a array.
 Top: pointer to keep track with the position of element inside the Stack.
 Max: the size of the Array. Which is also indicates the maximum (max – 1) components that the
Stack can have.

 Take the max value that is a variable.

 Set the max of stack equal to it.

 Creat an object “a” have the size “max”.

 Indicating the top variable to be “-1” which is show that the Stack is “null” Create stack with the size
of 50.

 Creating the Stack with the max size of 50 which means it can only have 50 elements.

 Stack is empty, top variable will be “-1”

 If returning “true”, first value “-1”. However, “false”, a number is positive.

 The stack is full or not, type the final number into the process table to know more accurately.

 The size of the stack is "max". Then the Stack is full when top = max - 1.

 The equation will be correct when it returns top = max -1.

 The clear() method is used to remove all of the elements from a list. The list will be empty after this
call returns.

Page 8
 The Boolean method increases the size of array a and also increases the size of the Stack.

 Declare temporary’s variable “max1”, a1 new Object that have the size of “max1”.

 Check if Object [] a1 is empty or not. If true then we give top = max -1, otherwise false will return
false and exit the method.

 A few more is to build object a in composition, copy each relative component a so that transform a
to [] a1.

 Set a and max to have the new values of a1[], max1 respectively.

 Return true.

 The method will take the Object x as a variable.

 First check whether the stack is at the limit or not and check if the new grow Object is null or not.

 If yes, return void.

 Else, add top with one and the component a[top] will be set with value “x” is the variable in the
function method to be found.

• First check whether the Stack empty or not. If yes, throw Exception that show null as error message.

This error will help us a[top] Decrease top by one.

• Return the Object x (the pop element).

Page 9
From the chart above we can see in order to convert 10 to a binary, we can use the stack system with push
and pop function, the number keeps divide by 2 and put into a stack and it gets pop out after there is no
more number to be divide (at zero) by the LIFO Last in First out rules we can get the above result.

Page 10
P5 Implement error handling and report test results.

Try catch:
When executing a certain piece of Java code, different errors can occur such as:
Error generated by the coder itself
Syntax error
Logical error
... things we might not have anticipated.
Use try catch in Programs:
When an exception or error occurs, Java will normally stop executing the program and issue a message, in other
words Java throws an exception.
Exception Handling in java is a mechanism to handle runtime errors in order to maintain the normal flow of the
application.
The process of handling exception is called catch exception. If Runtime System cannot handle the exception, the
program will terminate.
The try block in java is used to contain an executable code that might cause an exception during execution.
After a try block, you must declare either catch or finally blocks, or both.
The catch block in java is used to handle if an exception occurs, otherwise it is ignored.
The catch block must be used immediately after the try block. You can use multiple catch blocks with but only
one try block.
When there is no try catch in the program

Page 11
When the program is not using Try catch, an error will appear “RuntimeException”
Error " RuntimeException " is an message when enter the character data, structure, ... is not a integer
To want fix " RuntimeException " errors in the program we must use the try-catch command
RuntimeException will show an error when entering incorrect data in the program

when using try catch in program:

Then, I use try-catch to fix RuntimeException

+ If non-integer data is entered incorrectly, the “try” section will run and catch will “catch” an error

Then the program will show up a notice “error”. Then forces us to re-enter the correct integer

+ If correctly entered data is an integer

Try running the program and it will not error

Page 12
My program is finally running, when entering the correct integer.

When running in a chapter that already has try-catch, there will be no error

There will be no error “RuntimeException”

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

1. Analysis of Algorithms:

When we analyze algorithms, we should employ mathematical techniques that analyze algorithms
independently of specific implementations, computers, or data.

To analyze algorithms:

Page 13
o First, we start to count the number of significant operations in a particular solution to assess its
efficiency.

o Then, we will express the efficiency of algorithms using growth functions.

2. The Execution Time of Algorithms:

Each operation in an algorithm (or a program) has a cost.


Each operation takes a certain of time.

count = count + 1; take a certain amount of time, but it is constant.

A sequence of operations:

count = count + 1; Cost: c1 sum

= sum + count; Cost: c2

Total Cost = c1 + c2

Example: Simple If-Statement

Example: Simple Loop

Page 14
Example: Nested Loop

3. General Rules for Estimation:


Loops

The running time of a loop is at most the running time of the statements inside of that loop times the
number of iterations.

Nested Loops

Running time of a nested loop containing a statement in the inner most loop is the running time of
statement multiplied by the product of the sized of all loops.

Consecutive Statements

Just add the running times of those consecutive statements.

If/Else:

Page 15
Never more than the running time of the test plus the larger of running times of S1 and S2.

4. Algorithm Growth Rates:

We measure an algorithm’s time requirement as a function of the problem size.

o Problem size depends on the application: e.g. number of elements in a list for a sorting algorithm,
the number disks for towers of hanoi.

So, for instance, we say that (if the problem size is n).

▪ Algorithm A requires 5*n2 time units to solve a problem of size n.


▪ Algorithm B requires 7*n time units to solve a problem of size n.

The most important thing to learn is how quickly the algorithm’s time requirement grows as a function of
the problem size.

▪ Algorithm A requires time proportional to n2.

▪ Algorithm B requires time proportional to n.

An algorithm’s proportional time requirement is known as growth rate.

We can compare the efficiency of two algorithms by comparing their growth rates.

Page 16
5. Growth-Rate Functions – Example 1:

Page 17
6. Example using stack:

Page 18
My assessment is based on the theoretical description of the asymptotic analysis.

I think my algorithm responds immediately to requests made. For my requests, it is good to respond
immediately. I also tried other requests with longer numbers that needed to execute more commands,
my program still produced results almost instantly. I think that affecting the runtime of an algorithm
has many causes. The first is that if the request is made too long, the request may affect the running
time of the algorithm. The second is about whether my algorithm is optimal or not and whether there
is an error when the user makes a request or not.

Page 19
The type of structure I use here for this program is Abstract Data Type. My choice is the number of lines
of code that are quite long, but I think with their use this is necessary for the program. Besides, it helps
my program work more closely together and no errors when executing the requests. This also affects
the running time of the program, but I think it is not too time-consuming.

P7 Determine two ways in which the efficiency of an algorithm can be measured, illustrating your answer with
an example.

1. Algorithmic Performance:

There are two aspects of algorithmic performance:

Time

• Instructions take time.

• How fast does the algorithm perform?

• What affects its run time?


Space

• Data structures take space.

• What kind of data structures can be used?

• How does choice of data structure affect the run time?


We will focus on time

• How to estimate the time required for an algorithm.


• How to reduce the time required.

2. Analysis of Algorithms:
What is Analysis of Algorithms

In computer science, the analysis of algorithms is the process of finding the computational complexity of
algorithms – the amount of time, storage, or other resources needed to execute them.

How are the algorithms coded?

Comparing running times means comparing the implementations.

Page 20
We should not compare implementations, because they are sensitive to programming style that may cloud
the issue of which algorithm is inherently more efficient.
What computer should we use?

We should compare the efficiency of the algorithms independently of a particular computer.

What data should the program use?

Any analysis must be independent of specific data.


When we analyze algorithms, we should employ mathematical techniques that analyze algorithms
independently of specific implementations, computers, or data.

To analyze algorithms

First, we start to count the number of significant operations in a particular solution to assess its efficiency.

Then, we will express the efficiency of algorithms using growth functions.

3. Growth Rates:

Page 21
Figure 1: Growth Rate Named of the following function

Figure 2: Running time of 4 function at milliseconds

Figure 3: Figure show how much the function can execute at a specific running time

4. Order of Magnitude Analysis and Big O Notation:

If Algorithm A requires time proportional to f(n), Algorithm A is said to be order f(n), and it is denoted as
O(f(n)).

The function f(n) is called the algorithm’s growth-rate function.

Since the capital O is used in the notation, this notation is called the Big O notation.

If Algorithm A requires time proportional to n2, it is O(n2).

Page 22
If Algorithm A requires time proportional to n, it is O(n).

5. Definition of the Order of an Algorithm:

Definition

Algorithm A is order f(n) – denoted as O(f(n)) – if constants k and n0 exist such that A requires no more than
k*f(n) time units to solve a problem of size n ≥ n0.

The requirement of n ≥ n0 in the definition of O(f(n)) formalizes the notion of sufficiently large problems.

In general, many values of k and n can satisfy this definition.

If an algorithm requires n2–3*n+10 seconds to solve a problem size n. If constants k and n0 exist such that

 k*n2 > n2–3*n+10 for all n ≥ n0. the algorithm is order n2 (In fact, k is 3 and n0 is 2)

 3*n2 > n2–3*n+10 for all n ≥ 2.

Thus, the algorithm requires no more than k*n2 time units for n ≥ n0, So it is O(n2).

Figure 4: Order of an Algorithm

Page 23
Figure 5: A Comparison of Growth-Rate Functions

Figure 6: A Comparison of Growth-Rate Functions

Growth-Rate Functions
Functions Time Meaning

O(1) T(n)=1 Time requirement is constant

Time requirement for a logarithmic


T(n) = (1*log216) / log28 = 4/3 = 1.3
O(log2n) algorithm increases increase slowly as the
seconds
problem size increases.

Page 24
Time requirement for a linear algorithm
O(n) T(n) = (1*16) / 8 = 2 seconds increases directly with the size of the
problem.

Time requirement for a n*log2n algorithm


T(n) = (1*16*log216) / 8*log28 = 8/3
O(n*log2n) increases more rapidly than a linear
= 2.7 seconds
algorithm.

Time requirement for a quadratic algorithm


O(n2) T(n) = (1*162) / 82 = 4 seconds increases rapidly with the size of the
problem.

Time requirement for a cubic algorithm


increases more rapidly with the size of the
O(n3) T(n) = (1*163) / 83 = 8 seconds
problem than the time. requirement for a
quadratic algorithm.

As the size of the problem increases, the


T(n) = (1*216) / 28 = 28 seconds = time requirement for an exponential
O(2n)
256 seconds algorithm increases too rapidly to be
practical.
Table 1: Growth-Rate Functions

Properties of Growth-Rate Functions

We can ignore low-order terms in an algorithm’s growth-rate function.

 If an algorithm is O(n3+4n2+3n), it is also O(n3).

 We only use the higher-order term as algorithm’s growth-rate function.

We can ignore a multiplicative constant in the higher-order term of an algorithm’s growth-rate function.

 If an algorithm is O(5n3), it is also O(n3).

O(f(n)) + O(g(n)) = O(f(n)+g(n)).

 We can combine growth-rate functions.

 If an algorithm is O(n3) + O(4n), it is also O(n3 +4n2) 🡺 So, it is O(n3).

 Similar rules hold for multiplication.

Page 25
References
Unit 19 - Data Structures and Algorithms, Lecture 01 - ADT, University of Greenwich (Alliance with
Vietnam FPT Education), United Kingdom.
Unit 19 - Data Structures and Algorithms, Lecture 02 - Linked List, University of Greenwich (Alliance with
Vietnam FPT Education), United Kingdom.
Unit 19 - Data Structures and Algorithms, Lecture 03 - Stack and Queue, University of Greenwich (Alliance
with Vietnam FPT Education), United Kingdom.
Unit 19 - Data Structures and Algorithms, Lecture 04 - Recursion, University of Greenwich (Alliance with
Vietnam FPT Education), United Kingdom.
Unit 19 - Data Structures and Algorithms, Lecture 05 - Algorithm Analysis, University of Greenwich
(Alliance with Vietnam FPT Education), United Kingdom.
Vietjack.com. (2018). Khối try-catch trong Java [online] Available at:
https://vietjack.com/java/khoi_try_catch_trong_java.jsp [Accessed 24 Oct 2020].
AmanSingh2210. (2019). Logger log() Method in Java with Examples [online] Available at:
https://www.geeksforgeeks.org/logger-log-method-in-java-with-examples [Accessed 24 Oct 2020].
Wikipedia.org. (2020). Wikipedia [online] Available at:
https://en.wikipedia.org/wiki/Analysis_of_algorithms [Accessed 26 Oct 2020].

Page 26

You might also like