Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Vo Van Duc (FGW DN) - 301625 - 0-Đã Chuyển Đổi

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 38

ASSIGNMENT 2 FRONT SHEET

Qualification BTEC Level 5 HND Diploma in Computing

Unit number and title Unit 19: Data Structures and Algorithms

Submission date Date Received 1st submission

Re-submission Date Date Received 2nd submission

Student Name Võ Văn Đức Student ID GCD191230

Class Gcd0805 Assessor name Hồ Văn Phi

Student declaration

I certify that the assignment submission is entirely my own work and I fully understand the consequences of plagiarism. I understand that
making a false declaration is a form of malpractice.

Student’s signature Đức

Grading grid

P4 P5 P6 P7 M4 M5 D3 D4
 Summative Feedback:  Resubmission Feedback:
2.1

Grade: Assessor Signature: Date:


Internal Verifier’s Comments:

IV Signature:
Contents
P4 Implement a complex ADT and algorithm in an executable programming language to solve a welldefined problem.......................................................................................6
1. INTRODUCTION.............................................................................................................................................................................................................................................. 6
2. EXPLAIN THE PROBLEM CODE......................................................................................................................................................................................................................... 6
3. PROBLEM ANALYSIS AND SOLUTION........................................................................................................................................................................................................... 6
IV. CODING AND IMPLEMENTING....................................................................................................................................................................................................................... 9
1. Code............................................................................................................................................................................................................................................................ 9
P5 Implement Error Handling And Report Test Results.(P5)................................................................................................................................................................................. 11
I. Explain How You Handle Error By Exception.................................................................................................................................................................................................. 11
II. TEST (P5)................................................................................................................................................................................................................................................ 13
A Test case......................................................................................................................................................................................................................................................... 13
B.RESULT........................................................................................................................................................................................................................................................... 16
P6 Discuss how asymptotic analysis can be used to assess the effectiveness of an algorithm..............................................................................................................................22
I. Asymptotic analysis........................................................................................................................................................................................................................................ 22
II, Explain about big O with some simple example theory.................................................................................................................................................................................27
1. O(1) → Constant Time............................................................................................................................................................................................................................... 27
2. O(n) → Linear Time.................................................................................................................................................................................................................................... 28
3. O(n²) → Quadratic Time............................................................................................................................................................................................................................ 28
4. O(log n) → Logarithmic Time..................................................................................................................................................................................................................... 28
III. Present how to assess the effectiveness of an algorithm by using asymptotic analysis...............................................................................................................................29
IV: Assess complexity of Big Oh Notation O with 2 algorithms are Sorting and Searching................................................................................................................................29
Output........................................................................................................................................................................................................................................................... 32
Output........................................................................................................................................................................................................................................................... 33
P7: Determine two ways in which the efficiency of an algorithm can be measured, illustrating your answer with an example..........................................................................34
DEFINITION OF ALGORITHM EFFICIENCY........................................................................................................................................................................................................... 34
II. THE EFFICIENCY OF AN ALGORITHM DEPENDS ON HOW EFFICIENTLY IT USES TIME AND MEMORY SPACE.............................................................................................35
1. TIME EFFICIENCY........................................................................................................................................................................................................................................... 36
A. THEORY..................................................................................................................................................................................................................................................... 36
B. PRACTICE................................................................................................................................................................................................................................................... 36
2. SPACE EFFICIENCY.......................................................................................................................................................................................................................................... 36
3. TEST AND IMAGE VERIFICATION.................................................................................................................................................................................................................... 36
Figure 1sending model............................................................................................................................................................................................................................................ 7
Figure 2 flowchart................................................................................................................................................................................................................................................... 9
Figure 3 code......................................................................................................................................................................................................................................................... 10
Figure 4 result....................................................................................................................................................................................................................................................... 11
Figure 5 code try catch.......................................................................................................................................................................................................................................... 13
Figure 6 Test case.................................................................................................................................................................................................................................................. 16
Figure 7 result test case......................................................................................................................................................................................................................................... 20
Figure 8 Test Log................................................................................................................................................................................................................................................... 22
Figure 9 Big O Complexity..................................................................................................................................................................................................................................... 27
Figure 10 time and space...................................................................................................................................................................................................................................... 37
Figure 11time and space....................................................................................................................................................................................................................................... 37
P4 Implement a complex ADT and algorithm in an executable programming language to solve a welldefined
problem
1. INTRODUCTION
Today, most of the popular software applications today use different types of data structures,

uses a variety of algorithms to process different types of data to address user requests and

develop new solutions. different applications. Data structures help us to store and process

Faster and more efficient data to improve performance

In this section, I will build on what was mentioned in ASM1 about ADT . data types

structure, along with a combination of different algorithms to develop messaging

program (up to 250 characters) from source to destination.

2. EXPLAIN THE PROBLEM CODE


Using the Java programming language, develop a program that allows texting up to 250

characters from source to destination. This program must use at least two different data

structure (Queue, ArrayList, Stack, etc.) to act as a buffer during message passing. Print

In addition, the program needs to add the ability to handle errors and exceptions

in the implementation process.

3. PROBLEM ANALYSIS AND SOLUTION


Step 1: Create a message string input function that takes input from the user

keyboard and from the data entered by the user, do a string length check to do it

make sure that the string is valid (string cannot be larger than 250 characters) and the input string
cannot be left blank)

Step 2: Build a message handling function, maximum buffer when processing

message string has 10 characters for both ArrayList and Queue. Check the length of

message chain and check each element in both the message chain and the rest

buffer in the ArrayList, then do a loop that splits each element in the string and adds

ArrayList until ArrayList reaches 10 elements

Step 3: Check the length of the ArrayList, then get each character from the ArrayList and

add to the Queue and remove that character on the ArrayList. When the length of

ArrayList = 0 is equivalent to empty ArrayList, end of transfer.

Step 4: Check if the Queue is empty, create a loop to get each element present in

Queuing up to the message pick-up point. Stop the loop until Buffer

Empty queue.

➢ Algorithm analysis through diagram

Figure 1sending model

➢ Algorithm analysis through flowchart


Begin

YES
lenght

Yes

characters=S[i] arrayList add‹characters

1’ES

A full *

1’ES

characters = arrayList get(0)


queue add‹characters ›
Figure 2 flowchart

IV. CODING AND IMPLEMENTING


1. Code
Figure 3 code

2. Result
Figure 4 result

P5 Implement Error Handling And Report Test Results.(P5)


I.Explain How You Handle Error By Exception
When building the program, an error occurs when executing the program. To be able to grasp and give

information when encountering the above errors, we use Java Exceptions Try Catch to throw an exception.

Try: used to define a block of code that is checked for errors as they are executed

Catch: used to specify the actions to be executed when the code block in the Try section encounters an error

For my program, the purpose of using Try Catch here is to detect unexpected errors in the handling of transmitted messages like

between ArrayList and Queue like "Out of bounds in ArrayList, Queue did not receive the specified characters passed from
Arraylist, etc. Specifically, the way TryCatch works in my program is as follows:

1 - The try statement will contain all the code about loops and statements that handle operations like splitting a string into

character to highlight with ArrayList, get character from ArrayList and increment queue, get character from queue to maneuver

destination, etc.

2- The Catch statement will display the program's error messages, along with the associated error causes

3- When running the program, all statements in Try are executed, if an error occurs, assign the exception clause to the variable.

e will be thrown and passed to Catch.

4 - Catch receives the exception and executes the statements in its block. Print the message "PROGRAM ERROR!" together with details of the Attempted error detected.
Figure 5 code try catch

II. TEST (P5)


A Test case
Test What is How Data Expected result
being
test

1 Message Enter Send =” Asymptotic Analysis is Print out: “The message is


contains string has the big idea that handles above too long (>250 characters)”
more more than issues in analyzing algorithms. In
than 250 Asymptotic Analysis, we evaluate
250
characters the performance of an algorithm in
characters 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. (277
letters)

2 Message Enter string Send =” Print out:


contains has 50 Asymptotic Analysis is the big idea that “Asymptotic Analysis is the big idea that
50 characters handles above issues in analyzing handles above issues in analyzing
characters algorithms.” algorithms.”
3 Message Not enter Send =’’(0 Characters) Print out: “The message is empty”
not anything
contains
any
character
4 Message Enter string Send =” Asymptotic analysis” Print out: “ Asymptotic analysis”
contains has 20
20 characters
characters
5 Message Enter Send=” Print out: “
contains string has ☤☥☧☨☩☫ ☽♈” ☤☥☧☨☩☫ ☽♈”
only 50 special ☬☭ ☬☭
special characters
characters

Figure 6 Test case

B.RESULT
• CASE 1
 Case 2
 Case 3
 Case 4

 Case 5
Figure 7 result test case

C. TEST LOG TABLE

Case What is How Data Expected Date Actual result Action


being result Taken
1 Message Enter Send =” Message 28/08 None
contains string ABCDEFGABCDEF is too long /2021
more has more GABCDEFGABCD (>250
than 250 than 250 EFGABCDEFGABC characters)
character
character DEFGABCDEFGAA
s
s BCDE
FGABCDEFGABCD
EFGABCDEFGABC
DEFG
ABCDEFGABCDEF
GAABCDEFGA
BCDEFGABCDEFG
ABCDEFGABCDEF
GAB
CDEFGABCDEFGA
ABCDEFGABCDEF
GAB
CDEFGABCDEFGA
BCDEFGABCDEFG
ABC
DEFGAABCDEFGA
BCDEFGABCDEFG
ABC
DEFGABCDEFGAB
CDEFGABCDEFGA
YKSJJ” (255
Characters)

2 Message Enter Send =” Sending 28/08/ none


contains string ABCDEFGABCDEF success 2021
50 has 50
GABCDEFGABCDE
character characte
FGABCDE
s rs
FGABCDEFGABCD
E”
3 Message Not Send =’’ ”(0 Message 28/08/ none
not enter Characters) is 2021
contains anything empty
any
character
4 Message Enter Send =” Sending 28/08/ none
contains string ABCDEFGABCDED success 2021
20 has 20
SFADFFF”
character characte
s rs

Message Enter Send=” Sending 28/08/ none


contains string success 2021
only has 50
special special ☤☥☧☨
character characte
s
☩☫
rs
☬☭
☽♈”

Figure 8 Test Log

P6 Discuss how asymptotic analysis can be used to assess the effectiveness of an algorithm
I. Asymptotic analysis
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.

The asymptotic analysis defines the mathematical foundation of an algorithm’s run time performance. If there is no input to an algorithm then the algorithm
will always work in a constant time.

Asymptotic analysis is the running time of any process or algorithm in mathematical terms.
We can calculate the best, average, and worst-case scenarios for an algorithm by using asymptotic analysis.

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.

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

Asymptotic Notations

Following are the commonly used asymptotic notations to calculate the running time complexity of an algorithm.

1. Ο Notation
2. Ω Notation
3. θ Notation

Big Oh Notation, Ο

The notation Ο(n) is the formal way to express the upper bound of an algorithm's running time. It measures the worst case time complexity or the longest
amount of time an algorithm can possibly take to complete.
Omega Notation, Ω

The notation Ω(n) is the formal way to express the lower bound of an algorithm's running time. It measures the best case time complexity or the best amount of
time an algorithm can possibly take to complete.

Theta Notation, θ

The notation θ(n) is the formal way to express both the lower bound and the upper bound of an algorithm's running time
Common Asymptotic Notation:

Following is a list of some common asymptotic notations below:

constant − Ο(1)

logarithmic − Ο(log n)

linear − Ο(n)

n log n − Ο(n log


n)

quadratic − Ο(n2)
cubic − Ο(n3)

polynomial − nΟ(1)

exponential − 2Ο(n)
II, Explain about big O with some simple example theory
Big-O notation is the language we use for talking about how long an algorithm takes to run
(time complexity) or how much memory is used by an algorithm (space complexity). Big-O
notation can express the best, worst, and average-case running time of an algorithm. For our
purposes here, we are going to focus primarily on Big-O as it relates to time complexity.

Figure 9 Big O Complexity

1. O(1) → Constant Time

O(1) means that it takes a constant time to run an algorithm, regardless of the size of the
input.

Take a look at findFirstIndex, listed below.


Passing smallCollection or giganticCollection will produce the same runtime of O(1) when
accessing the 0 index. The return of firstIndex is also a constant time operation. Regardless of
the size of n, both of these operations will take a constant amount of time.
2. O(n) → Linear Time
O(n) means that the run time increases at the same pace as the input.

In programming, one of the most common linear-time operations is traversing an array. In


JavaScript, methods like forEach, map, and reduce run through the entire collection of data,
from start to finish.

Take a look at our printAllValues function below. The number of operations that it will take
to loop through n is directly related to the size of n. Generally speaking (but not always),
seeing a loop is a good indicator that the particular chunk of code you’re examining has a run
time of O(n).

3. O(n²) → Quadratic Time

O(n²) means that the calculation runs in quadratic time, which is the squared size of the input
data.

In programming, many of the more basic sorting algorithms have a worst-case run time of
O(n²):

 Bubble Sort
 Insertion Sort
 Selection Sort

4. O(log n) → Logarithmic Time


O(log n) means that the running time grows in proportion to the logarithm of the input size,
meaning that the run time barely increases as you exponentially increase the input.
In programming, this act of searching through a physical dictionary is an example of a
binary search operation — which is the most typical example used when discussing
logarithmic run times.

That n is now a number: n could be an input (number) or the size of an input (the length of
an array).

III. Present how to assess the effectiveness of an algorithm by using


asymptotic analysis
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.

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

IV: Assess complexity of Big Oh Notation O with 2 algorithms are Sorting and
Searching:
public class SelectionSort {
int[] array;

public SelectionSort() (
a may = new
int[100];

public SelectionSort(int [] a} {
a:may = new int[a.length];
for(int i = 0; i < a. ength; itt} (
array[i] = a[i];

public void swap(int a, int b} {


int temp = a;
public void sort () {
for(int j = 0, j < array.length - 1, jtt) (
int iMin = j,
for(int i = j + 1; i < array.length, i++) (
if(array[i] < array[iMin]›
iMin = i,

if(iMin !=j) (
int temp = array[jj,
array[j] = array[iMin],
array[iMin] = temp,

public void show() {


System.out.println(”The elements of array: ”),
for(int i = 0, i< array.length, i++)
System.our.println(” ” + array[i]),

public static void maim(String[] args) {


int n;
Scanner input = new Scanner(System.]u};
System.out.print‹”Input the number of array elements: ”);
n = input.nextInt();
int[] a = new int[n];
for‹int i = 0; i < n; itt) {
System.out.print("Input #" t i t ”:
”); a[i] = input.nextInt();

test = new SelectiouSort‹a);


System.out.println(”\nDisplay array: ”);
test.show();
System.out.println(”\nDisplay array after sorting: ”);
test.sort();
test.show();
Output
:

Time Complexity:

o Best Case: O(N2). Also O(N) swaps.


o Worst Case: Reversely sorted, and when inner loop makes
maximum comparison. O(N2).Also O(N) swaps.
o Average Case: O(N2). Also O(N) swaps.
Output:

Time Complexity:

 Best case is the element is at the head of the array, hence O(1).

 Worst case is when the desired element is at the tail of the array
or not present at all, in this case you have to traverse till the
end
of the array, hence the complexity is O(N).

 Average case is n(n+1)/2n = 0(N).


Although ordered linear search is better than unordered when the element
is not present in the array, the best and worst cases still remain the same,
with the key element being found at first position or at last position.

Effectiveness of the algorithm:

About Selection Sort: I can also be used on list structures that make add
and remove efficient, such as a linked list. Just remove the smallest
element of unsorted part and end at the end of sorted part. Bestcase
complexity is of O(N) while the array is already stored. Number of swaps
reduced O(N) swaps in all cases in-place sort.

Linear search is rarely used practically because other search algorithms


such as the binary searchalgorithm and hash tables allow significantly
faster searching comparison to Linear search.

P7: Determine two ways in which the efficiency of an algorithm can


be measured, illustrating your answer with an example.

DEFINITION OF ALGORITHM EFFICIENCY:


The efficiency of an algorithm is principally defined by two factors i.e. space and time. A good algorithm
is one that's taking less time and fewer space, but this can be unattainable all the time. there's a trade-
off between time and space. If you would like to cut back the time, then space might increase. Similarly,
if you want to cut back the space, then the time may increase. So, you've got to compromise with either
space or time.

Efficiency of an algorithm can be analyzed at two different stages, before implementation and after
implementation. They are the following −

An algorithm's efficiency can be assessed at two stages: prior to implementation and after
implementation. The following are some of them:
 An algorithm's a priori analysis is a theoretical examination of the algorithm. The efficiency of
an algorithm is determined by assuming that all other variables, such as processor speed,
remain constant and have no impact on its implementation.
 A Posterior analysis of an algorithm is known as a posterior analysis. A programming language is
used to implement the chosen algorithm. The program is then run on the target computer
machine. Actual statistics like as running time and required space are obtained in this
investigation..

A Posteriori analysis A priori analysis


Posteriori analysis is a relative analysis. Piori analysis is an absolute analysis.
It is dependent on language of compiler It is independent of language of compiler and
and type of hardware. types of hardware.
It will give exact answer. It will give approximate answer.
It doesn’t use asymptotic notations to It uses the asymptotic notations to represent how
represent the time complexity of an much time the algorithm will take in order to
algorithm. complete its execution.
The time complexity of an algorithm The time complexity of an algorithm using a priori
using a posteriori analysis differ from analysis is same for every system.
system to system.
If the time taken by the algorithm is less, If the program running faster, credit goes to the
then the credit will go to compiler and programmer.
hardware.

We shall learn about a priori algorithm analysis. Algorithm analysis deals with the execution or running
time of various operations involved. The running time of an operation can be defined as the number.

II. THE EFFICIENCY OF AN ALGORITHM DEPENDS ON HOW EFFICIENTLY


IT USES TIME AND MEMORY SPACE.
The time efficiency of an algorithm is measured by various factors. as an example, write a
program for an outlined algorithm, execute it by using any programing language, and measure
the full time it takes to run. The execution time that you just measure during this case would
depend upon variety of things such as:

• Speed of the machine


• Compiler and other system Software tools
• Operating System
• Programming language used
• Volume of data required

Two ways are used to measure the effectiveness of the algorithm:


1. TIME EFFICIENCY
Time efficiency is a function describing the amount of time an algorithm takes in terms of the
amount of input to the algorithm. "Time" can mean the number of memory accesses
performed, the number of comparisons between integers, the number of times some inner
loop is executed, or some other natural unit related to the amount of real-time the algorithm
will take.

- When analyzing for time complexity we can take two approaches:

A. THEORY:
Analyze the algorithm, typically using time complexity analysis to get an estimate of the
running time as a function of the size of the input data.  Estimation of running time:
• Method 1 Operation counts: select operation(s) that are executed most frequently and
determine how many times each is done.
• Method 2 Step counts: determine the total number of steps, possibly lines of code,
executed by the program.
 The actual running time depends on many factors:
• The speed of the computer: CPU (not just clock speed), I/O, etc.
• The compiler, compiler options.
• The quantity of data.
• The actual data last.
B. PRACTICE
Use a benchmark to time the use of an algorithm. Many programming languages have an
available function which provides CPU time usage.

By execution of the code we can:


• Benchmark: run the program on various data sets and measure the performance.
• Profile: A report on the amounts of time spent in each routine of a program, used to
find and tune away the hot spots in it.

2. SPACE EFFICIENCY
Is a function describing the number of memory (space) an algorithm takes in terms of the
number of input to the algorithm. we frequently speak of "extra" memory needed, not
counting the memory needed to store the input itself. Again, we use natural (but fixedlength)
units to live this. we will use bytes, but it's easier to use, say, number of integers used,
number of fixed- sized structures, etc. within the end, the function we come up with are
independent of the particular number of bytes needed to represent the unit. Space
complexity is typically ignored because the space used is minimal and/or obvious, but
sometimes it becomes as important a difficulty as time.

3. TEST AND IMAGE VERIFICATION


Case 1 : Size of Q is 20 elements, time to send 200 characters from S to D is 0,3ms.
Space = 20 * 2 bytes = 40 bytes of RAM

Time : 0,3ms

Figure 10 time and space

Case 2 : Size of Q is 50 elements, time to send 200 characters from S to D is 0,1ms.

Space = 50 * 2 bytes = 100 bytes of RAM

Time : 0,1ms

Figure 11time and space

EFE ENCE
Data Structures - Algorithms Basics. (n.d.). Retrieved from
https://www.tutorialspoint.com/data_structures_algorithms/algorithms_basics.htm
Index of comments

2.1 Good points:


P4: An executable program to send a text message is implemented.
P5: Error handling and report test results are included in the report.
P6: Asymptotic analysis used to assess the effectiveness of an algorithm is discussed.
P7: Two ways in which the efficiency of an algorithm can be measured are illustrated with an example.

Week points:
+ Format of the report is not good
+ Writing skill is limited.

Should do:
+ Improve writing skill
+ Study and practice hard

You might also like