You are on page 1of 24

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 Nguyen Ngoc Tu

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.

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 1
should demonstrate some important operations of these structures. Even it’s a demo, errors should be handled
carefully by exceptions and some tests should be executed to prove the correctness of algorithms / operations.

The team needs to write a report of the implementation of the 2 data structures and how to measure the efficiency
of related algorithms. The report should also evaluate the use of ADT in design and development, including the
complexity, the trade-off and the benefits.

Learning Outcomes and Assessment Criteria

Pass Merit Distinction

LO1 Implement complex data structures and algorithms

P4 Implement a complex ADT M4 Demonstrate how the D3 Critically evaluate the


and algorithm in an executable implementation of an
complexity of an implemented
programming language to solve a ADT/algorithm solves a well- ADT/algorithm
well defined problem. defined problem

P5 Implement error handling


and report test results.

LO4 Assess the effectiveness of data structures and algorithms

P6 Discuss how asymptotic M5 Interpret what a trade-off is


analysis can be used to when specifying an ADT using D4 Evaluate three benefits of
assess the effectiveness of an an example to support your using implementation
algorithm answer independent data structures
P7 Determine two ways in
which the efficiency of an
algorithm can be measured,
illustrating your answer with
an example.

Page 2
LO1 Implement complex data structures and algorithms .................................................................................................. 4

P4 Implement a complex ADT and algorithm in an executable programming language to solve a well defined
problem ...................................................................................................................................................................... 4

1. The well defined problem: Convert 10 to binary ........................................................................................... 4

1.1. Decimal to Binary using Stack............................................................................................................ 4

1.2. Implement a complex ADT (e.g. Linked List) and algorithm (convert 10 to binary) in an executable
programming language to solve a well defined problem ........................................................................... 5

P5 Implement error handling and report test results ................................................................................................ 10

LO4 Assess the effectiveness of data structures and algorithms...................................................................................... 13

P6 Discuss how asymptotic analysis can be used to assess the effectiveness of analgorithm ................................. 13

1. Analysis of Algorithms ................................................................................................................................ 13

2. The execution time of algorithms ................................................................................................................ 14

3. General rules for estimations ....................................................................................................................... 15

4. Algorithm growth rates ................................................................................................................................ 15

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

1. Algorithmic Performance ............................................................................................................................ 17

2. Analysis of algorithms ................................................................................................................................. 17

3. Common growth rates .................................................................................................................................. 18

4. Order-of-Magnitude Analysis and Big O Notation ...................................................................................... 19

5. Order of an Algorithm ................................................................................................................................. 20

6. Growth-Rate functions ................................................................................................................................. 20

Reference ......................................................................................................................................................................... 24

Page 3
LO1 Implement complex data structures and algorithms

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


well defined problem.
1. The well defined problem: Convert 10 to binary

1.1. Decimal to Binary using Stack:

➢ To do this math we have the following principles:

✓ Divide the number to be converted by 2 (the result is the integer), then divide by 2 (and only take the
integer part), the resulting binary number is the set of the rest of the parts.

✓ First, we divide 10 by 2 and the result is 5 and remainder 0.

✓ Next, we divide 5 by 2, the result is 1 and remainder 1.

✓ Then, we divide 2 by 2, the result is 1 and the remainder is 0.

✓ Finally, we divide 1 by 2, the result is 0 and the remainder is 1.

➢ The binary number we obtained is the set of remainders of division and the number 10 in binary
is 0101.

➢ Example:

import java.util.*;class DecimalBinaryStack{


public static void main(String[] args)
{
Scanner in = new Scanner(System.in);

// Create Stack object


Stack<Integer> stack = new Stack<Integer>();

Page 4
// User input
System.out.println("Enter decimal number: ");
int num = in.nextInt();

while (num != 0)
{
int d = num % 2;
stack.push(d);
num /= 2;
}

System.out.print("\nBinary representation is:");


while (!(stack.isEmpty() ))
{
System.out.print(stack.pop());
}
System.out.println();
}
}

➢ Out put:

Enter decimal number: 999


Binary representation is:1111100111

1.2. Implement a complex ADT (e.g. Linked List) and algorithm (convert 10 to binary) in an
executable programming language to solve a well defined problem

1.2.1. LinkedList implementation of Stack

➢ Code:

public class LinkedListStack {

LinkedList h;

public LinkedListStack() {

h = new LinkedList();

public boolean isEmpty(){

return h.isEmpty();

public void push(Object x){

Page 5
h.addLast(x);

public Object pop(){

if(isEmpty()) return null;

return h.removeLast();

class LinkedListStack {
MyList h;
public LinkedListStack(){
h=new MyList();
}
public boolean isEmpty(){
return h.isEmpty();
}
public void push(int x){
h.addTail(x);
}
public Object pop(){
if(isEmpty()) {
return null;
}
return h.deleteTail();
}

➢ Example using stack:

public class ArrayStackImp {

public static void decToBin(int k){

ArrayStack s = new ArrayStack ();

System.out.println(k + " in binary system is: ");

Page 6
while(k>0){

s.push(new Integer(k%2));

k=k/2;

while(!s.isEmpty()){

System.out.print(s.pop());

System.out.println("");

package com;
class LinkedListStack {
MyList h;
public LinkedListStack(){
h=new MyList();
}
public boolean isEmpty(){
return h.isEmpty();
}
public void push(int x){
h.addTail(x);
}
public Object pop(){
if(isEmpty()) {
return null;
}
return h.deleteTail();
}
public static void main(String args[]){ LinkedListStack
lls=new LinkedListStack(); lls.push(120);
System.out.println("Element removed from LinkedList:" +lls.pop());
System.out.println("Element removed from LinkedList:" +lls.pop());
lls.push(130);

Page 7
System.out.println("Element removed from LinkedList: "+lls.pop());
}
}

➢ Out put:

➢ I use Stack to change the coefficients.

✓ Enter any int.

✓ Put the remainder of k chi for 2 (k% 2) on the stack.

✓ Assign k = k / 0

✓ Reverse the stack I get the value to count.

➢ Code in Javascript:

public class ArrayStack {


protected Object[] a;
int top;
int max;
public ArrayStack(final int max){
this.max = max;
a = (Object[]) new Object();
top=-1;
}
public ArrayStack(){
this(4);
}
public boolean isEmpty(){
return top == max -1;
}
public void clear(){
top = -1;
}
public boolean grow(){

Page 8
final int max1=max+max/2;
final Object[] a1 = new Object[max1];
for (int i = 0; i <= top; i++) {
a1[i]=a[i];
}
a=a1;
max=max1;
return true;
}
public void push(final Object x){
if(isFull() &&!grow())return;
a[++top] = x;
}

private boolean isFull() {


return false;
}

public Object top() {


if(isEmpty());
return(a[top]);
}
public Object pop(){
final Object x = a[top];
top--;
return x;
}
public void printStack(){
for (int i =0; i <= top;i++){
System.out.println(a[i] +",");
}
}
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()){
Page 9
System.out.println(s.pop());
}
System.out.println("");
}
}

➢ Out put:

P5 Implement error handling and report test results.

➢ The initial value is divided by 0 (k = k / 0), the program is terminated and an error message is displayed.

➢ Code:

public class ArrayStackImp {

public static void main(String[] args) {

decToBin(12);

public static void decToBin(int k) {

ArrayStack s = new ArrayStack();

System.out.println(k + "In Baniry System Is: ");

while(k % 2);

k = k / 0;

while(!s.isEmpty()) {

System.out.print(s.pop());

Page 10
}

System.out.println("");

➢ Result:

➢ So I used the try-catch command to skip it and the execution could continue.

➢ Code:

public class ArrayStackImp {

public static void main(String[] args) {

decToBin(12);

Page 11
System.out.println("End Of Main");

catch(Exception e) {

System.out.println("In the catch Block due to Exception: " + e);

public static void decToBin(int k) {

ArrayStack s = new ArrayStack();

System.out.println(k + "In Baniry System Is: ");

while(k % 2);

k = k / 0;

while(!s.isEmpty()) {

System.out.print(s.pop());

System.out.println("");

Page 12
➢ Result:

LO4 Assess the effectiveness of data structures and algorithms.

P6 Discuss how asymptotic analysis can be used to assess the effectiveness of analgorithm.
1. Analysis of Algorithms:

➢ Asymptotic analysis of an algorithm refers to defining the mathematical boundation/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.

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

Page 13
2. The execution time of algorithms:

➢ Each operation in an algorithm (or a program) has a cost. It leads to the situation that each operations
take a certain of time, but it is constant.
➢ A sequence of operation:

✓ count = count + 1; Cost : c1

✓ sum = sum + count; Cost : c2

Total Cost = c1 + c2

➢ Example:

Simple If-Statement

if (n<0)
absval = -n
else
absval = n;

➢ Total Cost <= c1+ max (c2,c3)

Simple Loop

i = 1;
sum = 0;
while (i <= n) {
i = i + 1;
sum = sum + 1;
}

➢ Total Cost = c1 + c2 + (n+1) * c3 + n * c4 + n* c5

Nested Loop

i = 1;
sum = 0;
while (i <= n){
j = 1;
while (j <= n) {
sum = sum + 1;

Page 14
j = j + 1;
}
i = i +1;
}

➢ Total Cost = c1 + c2 + (n+1)*c3 + n*c4 + n*(n+1)*c5+n*n*c6+n*n*c7+n*c8

➢ The time required for this algorithm is proportional to n2.

3. General rules for estimations:

➢ 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: 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.


✓ 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 15
Figure 1: Algorithm Growth Rates

Example:

i = 1;
sum = 0;
while (i <= n) {
i = i+ 1;
sum = sum + 1;
}

➢ T(n) = c1 + c2 + (n+1)* c3 +n*c4 +n*c5

= (c3+c4+c5)8n + (c1+c2+c3)

= a*n +b

➢ So, the growth-rate function for this algorithm is O(n).

Page 16
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:

✓ First, this is the time:

❖ Instructions take time.

❖ How fast does the algorithm perform?

❖ What affects its run-time?

✓ Secondly, this is the 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:

➢ How do we compare the time efficiency of two algorithms that solve the same problem: implement
these algorithms in a programming language (C++), and run them to compare their time requirement:

✓ How are the algorithms coded?

✓ Comparing running times means comparing the implementations.

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

Page 17
➢ What data should the program use?

✓ Any analysis must be independent of specific data.

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

➢ To analyse algorithm:

✓ 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 the growth functions.

3. Common growth rates:

Function Growth Rate Name

c Constant

log N Logarithmic

Log2N Log-squared

N Linear

N log N

N2 Quadratic

N3 Cubic

2N Exponential

Page 18
Figure 2: Running Time (milliseconds)

Figure 3: Running Time (seconds)

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 19
✓ If Algorithm A requires time proportional to n, it is O(n).

5. Order of an Algorithm:

➢ Definition of the order of an algorithm:

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

➢ 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 an Algorithm

6. Growth-Rate functions:

Page 20
Figure 5: Comparison of Growth-Rate functions

✓ O(1): Time requirement is constant, and it is independent of the problem’s size.

✓ O(log2n):Time requirement for a logarithmic algorithm increases increases slowly as the problem
size increases.

✓ O(n): Time requirement for a linear algorithm increases directly with the size of the problem.

✓ O(n*log2n): Time requirement for a n*log2n algorithm increases more rapidly than a linear
algorithm.

✓ O(n2): Time requirement for a quadratic algorithm increases rapidly with the size of the problem.

✓ O(n3): Time requirement for a cubic algorithm increases more rapidly with the size of the problem
than the time requirement for a quadratic algorithm.

✓ O(2n): As the size of the problem increases, the time requirement for an exponential algorithm
increases too rapidly to be practical.

➢ If an algorithm takes 1 second to run with the problem size 8, what is the time requirement
(approximately) for that algorithm with the problem size 16?

➢ If its order is:

✓ O(1): T(n) = 1 second

✓ O(log2n): T(n) = (1*log216) / log28 = 4/3 seconds =1.3 seconds

✓ O(n): T(n) = (1*16) / 8 = 2 seconds

✓ O(n*log2n): T(n) = (1*16*log216) / 8*log28 = 8/3 seconds =2.7 seconds

Page 21
✓ O(n2): T(n) = (1*162) / 82 = 4 seconds

✓ O(n3): T(n) = (1*163) / 83 = 8 seconds

✓ O(2n): T(n) = (1*216) / 28 = 28 seconds = 256 seconds

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

➢ Example:

i = 1;
sum = 0;
while (i <=n){
j = 1;
while (j <= n){
sum = sum + i;
j = j + 1;
}
i = i + 1;
}

T(n) = c1 + c2 + (n+1)*c3 + n*c4 + n*(n+1)*c5+n*n*c6+n*n*c7+n*c8

= (c5+c6+c7)*n2 + (c3+c4+c5+c8)*n + (c1+c2+c3)

= a*n2 + b*n + c

➢ So, the growth-rate function for this algorithm is O(n2)

Page 22
Page 23
Reference:
[1] beginnersbook.com. 2020. Java Program To Convert Decimal To Binary. [online] Available at:
<https://beginnersbook.com/2014/07/java-program-to-convert-decimal-to-binary/> [Accessed 27 October 2020].

[2] Niithanoi.edu.vn. 2020. Cách Sử Dụng TRY CATCH Trong JAVA Xử Lý Tất Cả Ngoại Lệ. [online] Available at:
<https://niithanoi.edu.vn/try-catch-trong-java.html> [Accessed 27 October 2020].

[3] beginnersbook.com. 2020. Try Catch In Java - Exception Handling. [online] Available at:
<https://beginnersbook.com/2013/04/try-catch-in-java/> [Accessed 27 October 2020].

[4] Tutorialspoint.com. 2020. Data Structures - Asymptotic Analysis - Tutorialspoint. [online] Available at:
<https://www.tutorialspoint.com/data_structures_algorithms/asymptotic_analysis.htm#:~:text=Asymptotic%20analysis%20of
%20an%20algorithm,of%20its%20run-
time%20performance.&text=Asymptotic%20analysis%20is%20input%20bound,other%20factors%20are%20considered%20
constant.> [Accessed 29 October 2020].

[5] Web.engr.oregonstate.edu. 2020. [online] Available at:


<http://web.engr.oregonstate.edu/~sinisa/courses/OSU/CS261/CS261_Textbook/Chapter04.pdf> [Accessed 29 October
2020].

[6] Math.fsu.edu. 2020. [online] Available at: <https://www.math.fsu.edu/~pkirby/mad2104/SlideShow/s4_4.pdf> [Accessed


29 October 2020].

[7] 2020. [online] Available at: <https://www.quora.com/What-is-the-meaning-of-order-of-growth-in-algorithm-analysis-and-


how-can-we-find-the-order-of-growth-of-given-algorithm> [Accessed 29 October 2020].

[8] Runestone.academy. 2020. 3.3. Big-O Notation — Problem Solving With Algorithms And Data Structures. [online]
Available at:
<https://runestone.academy/runestone/books/published/pythonds/AlgorithmAnalysis/BigONotation.html#:~:text=The%20orde
r%20of%20magnitude%20function,of%20steps%20in%20the%20computation.> [Accessed 29 October 2020].

[9] Cse.unl.edu. 2020. [online] Available at: <http://cse.unl.edu/~goddard/Courses/CSCE310J/Lectures/Lecture2-


AlgorithmAnalysis.pdf> [Accessed 29 October 2020].

[10] Sciencedirect.com. 2020. Algorithm Performance - An Overview | Sciencedirect Topics. [online] Available at:
<https://www.sciencedirect.com/topics/computer-science/algorithm-performance> [Accessed 29 October 2020].

Page 24

You might also like