Tải bản đầy đủ (.pdf) (30 trang)

Assignment 1 Data Structure and Algorithms (1649) Greenwich

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (1.92 MB, 30 trang )

ASSIGNMENT 1 FRONT SHEET
Qualification

BTEC Level 5 HND Diploma in Computing

Unit number and title

Unit 19: Data Structures and Algorithms

Submission date

24/08/2022

Date Received 1st submission

Re-submission Date

24/08/2022

Date Received 2nd submission

Student Name

Nguyen Manh Tung

Student ID

GCH200064

Class


GCH0907

Assessor name

Do Hong Quan

1.1

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

Grading grid
P1

P2

P3

M1

M2

M3

D1

D2



 Summative Feedback:

Grade:

 Resubmission Feedback:

Assessor Signature:

Internal Verifier’s Comments:

IV Signature:

Date:


Contents
Introduction......................................................................................................................................................... 1

I.
II.
1.

ADT .................................................................................................................................................................. 1

2.

Stack ADT ....................................................................................................................................................... 1


3.

Stack memory.................................................................................................................................................. 5

4.

Queue ADT ...................................................................................................................................................... 6

5.

Sorting algorithms ........................................................................................................................................ 10

III.

Specific Language ......................................................................................................................................... 20

1.

Introduction to formal specification, types ................................................................................................. 20

2.

VDM for Stack .............................................................................................................................................. 21

IV.

V.

ADT .................................................................................................................................................................. 1


Advantages of encapsulation and information hiding when using an ADT ............................................ 23

1.

Introduction encapsulation .......................................................................................................................... 23

2.

Advantages of encapsulation and information hiding when using an ADT ............................................ 24
Conclusion ......................................................................................................................................................... 25

References list............................................................................................................................................................ 25


List of figures
Figure 1: Abstract data type model (GeeksforGeeks, 2022)......................................................................................... 1
Figure 2: Practical example for Stack ............................................................................................................................ 2
Figure 3: push to stack .................................................................................................................................................. 3
Figure 4: pop() of stack ................................................................................................................................................. 3
Figure 5: peek() of stack................................................................................................................................................ 4
Figure 6: empty() of stack ............................................................................................................................................. 4
Figure 7: search operation of stack .............................................................................................................................. 5
Figure 8: Example to explain stack memory ................................................................................................................. 5
Figure 9: Example of stack memory (1) ........................................................................................................................ 6
Figure 10: Example of stack memory (2) ...................................................................................................................... 6
Figure 11:Real-world example for Queue..................................................................................................................... 7
Figure 12: enQueue of Queue ...................................................................................................................................... 8
Figure 13: deQueue of Queue ...................................................................................................................................... 8
Figure 14:isEmpty of Queue ......................................................................................................................................... 9
Figure 15: getFront of Queue ....................................................................................................................................... 9

Figure 16: search of Queue ......................................................................................................................................... 10
Figure 17: Flowchart of selection sort ........................................................................................................................ 12
Figure 18: Example of selection sort (1) ..................................................................................................................... 12
Figure 19: Example of selection sort (2) ..................................................................................................................... 13
Figure 20: Example of selection sort (3) ..................................................................................................................... 13
Figure 21: Example of selection sort (4) ..................................................................................................................... 13
Figure 22: Source code of selection sort .................................................................................................................... 14
Figure 23: Flowchart main of quick sorting ................................................................................................................ 16
Figure 24: Flowchart quick function ........................................................................................................................... 16
Figure 25: Quick sort example (1) ............................................................................................................................... 17
Figure 26: Quick sort example (2) ............................................................................................................................... 17
Figure 27: Quick sort example (3) ............................................................................................................................... 18
Figure 28: : Quick sort example (4) ............................................................................................................................. 18
Figure 29: Quick sort example (5) ............................................................................................................................... 19
Figure 30: Quick sort example (6) ............................................................................................................................... 19
Figure 31: Input array ................................................................................................................................................. 20
Figure 32: quick function ............................................................................................................................................ 20
Figure 33: Basic types of VDM (Wikipedia, 2021) ....................................................................................................... 21
Figure 34: Example of encapsulation for ADT (Bank system) ..................................................................................... 24


I.

Introduction

Abstract data type is an important data type for programming, especially for beginners. ADTs such as
Stack, Queue will be introduced with the application of Stack, memory stack. Algorithms are an
important part of programming, it has many applications in system and software development. Sorting
is a type of algorithm that helps to sort lists in a certain order. Selection sort and quick sort will be done
in this report. Then a specification language will be used for the stack, along with the reasons why

encapsulation should be used for the ADT.
II.
ADT
1. ADT
According to Datta, an abstract data type (ADT) is a data type that helps to hide their complexity, users
do not need to care about its implementation, it also provides functions for users to easily interact with
data types like add, delete, search (Datta, 2021). An ADT consists of a list of data (integers, strings,
etc.), with functions to perform operations on that data or its own subset of data. The purpose of ADT
is to simplify and hide the complexity of the data type as well as make the functionality available to the
user, bringing the complexity into the classes.

Figure 1: Abstract data type model (GeeksforGeeks, 2022)

Simply put, it provides users with public functions to use and hides the complexity of handling those
functions, users do not need to re-program from scratch but just use the built-in functions. This saves
time, ADTs are always updated with corrections and optimizations over time. Some popular ADT like
List, Stack, Queue.
2. Stack ADT
Before learning about Stack, the concept of Linear structure will be introduced. A set of data has a linear
structure, the elements will be arranged in a specified order, it has 2 ends, bottom and top or left and
1


right, can only access elements sequentially. Elements are usually linked in a sequential manner and
consume linear memory space. Stack and Queue are linear data structures.
Stack is an ADT with top-down data structure, things like adding elements and removing elements are
done on top of the Stack structure. It is a linear data structure because the data set is ordered in ascending
order, the first in first, the last in second, can only access the elements in sequence (it cannot be go
directly from bottom to top). Stack's sorting principle is called LIFO (last in, first out) ie the element
added to the end will be accessed first, then the element below it.

The practical example for Stack is a stack of disks, if you want to remove the bottom disk, you have to
take it from the top, otherwise if you want to add a new one, you have to leave it on the top.

Figure 2: Practical example for Stack

a. Overview stack operations
 push (Element item): Add an item of data type Element to the top of the stack, return true
(successful), false (failed).
 pop (): Remove an item from the top of the stack and return its value.
 peek (): Get the value on the top of the stack.
 empty (): Checks if the stack has an item, returns true if true, returns false if false.
 search (Object s): Checks and returns the item's position in the stack.
b. push(Element item) function
How it works: The function will take the input value of an item of data type Element, and then check if
the stack is full. Finally, perform a push operation, the value will be added to the top position of the
stack and push the previous element down, ie the new element will be the top of the stack. Success
returns true, failure (full stack limit or full memory, ...) returns false.

2


Figure 3: push to stack

After pushing 6 onto the stack, 6 becomes the top instead of 5, return true.
c. pop() function
How it works: The pop() function checks whether the stack is empty or not, if empty, returns null, if
there is an element, deletes that element from the stack, the top element after deletion will be the element
below. Returns the deleted value.

Figure 4: pop() of stack


Do pop() with stack S, the top element (5) will be removed, the return value will be 5. The purpose of
returning the deleted value is so that the user knows what the deleted value is or uses it for something
else.

3


d. peek() function
How it works: The peek() function checks
whether the stack is empty or not, if
empty, returns null, if not, returns the top
value of the stack. This function does not
change anything of the stack, it only has
the purpose of returning the top value of
the stack to the user.

Figure 5: peek() of stack

Do peek() with stack S, the top element (1) will be return, stack S does not change.
e. empty() function
How it works: The empty() function will check if the stack is empty, if the stack has an item, return
false, if the stack is null, return true. This function does not change the stack.
For example: Stack S has an item of 9, returns false, ie the stack is not empty.

Figure 6: empty() of stack

f. search(Object s)
How it works: The function will check if the stack is null or not, if null, return null, if there is an item,
use equals to check the items of the stack against the input object. If the condition is true, return the

position of that item relative to the top (top = 1), if the condition is not satisfied with the whole stack,
return -1. If there are multiple matching elements, take the element closest to the vertex.

4


Figure 7: search operation of stack

Do search(9) with stack S, check the condition from the top down, at position = 2 the condition is
satisfied, stop and return position = 2. This function does not change the stack.
g. Application
Stack ADT is commonly used in the system, its applications can be divided into 2 types: hardware and
software. In which the application for hardware is built-in to the hardware, has a dedicated memory and
is managed entirely by the system's hardware. Software applications are controlled by software, often
used to store variables while running the program.
Some practical applications: converting expressions to low-level languages, machine languages for
computers to perform; store variables to use, hold information, program functions, active subfunctions,
reverse the string (heap, stack).
3. Stack memory
Memory stack is a memory area of the system, it is used to store variables and functions when running
the program, after the function ends, it will delete and free the memory cell that stores that function. The
main memory stack operations are push (push a variable, function into stack memory) and pop (delete
position to release memory).
Applications in storing memory cells for recursive functions, for example, calculating the results of the
recursive multi function below, the variable
result will be stored on the stack, the multi
function (4) will also be stored on the stack to
wait for the results. after calculation. Each
recursive call will have an extra memory cell to
store the multi function, when multi (1) will have

a return value of 1, then calculate the value of
Figure 8: Example to explain stack memory

5


multi (2), multi (3) ,multi (4) and free the stack memory. Finally return the value for the variable result
at Main.

Figure 9: Example of stack memory (1)

Figure 10: Example of stack memory (2)

4. Queue ADT
Like Stack, Queue is a linear data structure because items are stored in a specified order. The difference
of Queue compared to Stack is that the sorting principle, Queue's sorting principle is FIFO (first in, first
out), ie the first items (front) will be processed first, the last items. (rear) will be processed in the end.

6


Queue operations also follow this principle, newly added items will be placed at the rear, processed
items will be in order starting from the front.
A real-world example of Queue is queuing, first come first served and last in line, buyers will be first in
line, purchases will be in order from front to rear.

Figure 11:Real-world example for Queue

a. Overview Queue operations
 enQueue(Element q): Push an item of data type Element to the end of the Queue (rear) and return

true on success, false on failure.
 deQueue(): Removes the first element of the Queue (front) and returns that value if deletion
succeeds, returns null if deletion fails.
 isEmpty(): Checks whether the Queue has an element, returns true if the Queue is empty, returns
false if the Queue has an item.
 getFront(): Gets the front element of the Queue without removing it, returns front on success, null
on failure.
 search(Object q): Checks and returns the same element as the input Object, returns the position of
the item found closest to the front, if not found, returns null.
To illustrate Queue operations, a scenario will be shared for operations.
Scenario (Practical example): A pizza shop with an online sales system, this system needs to get the
name of the pizza buyer. Every time a customer is imported, that customer will be saved after the
previous customers. The customer at the top will be given pizza by the staff, continuing to the next
customers.

7


Management wants to have functions such as checking the list has customers or not, get the name of the
first customer at golden hour to save in the promotion list, but do not delete that customer's name because
they have not bought pizza, Searches for 1 customer based on name and returns their position in the list
b. enQueue(String customer) function
The enQueue function will push the item of type Element to the rear position of the queue, the old rear
position will be pushed down. Successful execution returns true, failed execution (queue full or memory
full) returns false. If the Queue does not have an element, the item being pushed is both front and rear.

Figure 12: enQueue of Queue

Application to Scenario: Add the customer's name to the pizza queue. Using enQueue(“Trong”), the
rear position of Q will be changed to “Trong”, return true.

c. deQueue() function
The deQueue function is used to delete the Item at the front position of the Queue and return that item
if the deletion is successful. If delete fails for a reason such as an empty Queue then null is returned.
After deleting, the next item will be the front position.

Figure 13: deQueue of Queue

8


Application to Scenario: Delete the name of the customer who finished buying pizza at the store and
return the name of the customer who bought it for confirmation, this customer name can be saved in the
store's purchase history.
d. isEmpty() function
The isEmpty function will check if the Queue has any items, if the Queue is empty, it returns true, if the
Queue has an item, it returns false.

Figure 14:isEmpty of Queue

Application to Scenario: The isEmpty function will check if there are any customers on the waiting
list for pizza, in which case there are no customers, so return true. The store uses this function to make
sure there aren't any customers ordering pizza.
e. getFront() function
The getFront function will retrieve the front of the Queue, return the front value if successful, if the
Queue is empty, return null. The function does not change the Queue.

Figure 15: getFront of Queue

Application to Scenario: Use getFront() to get the lucky person in first place at golden hour (8:00).
Returns the name of the person in the first place, the restaurant can save this name in the weekly winner

list for awarding.
9


f. search(Object customer) function
The search function searches for the item that is the same as the input Object and that item is closest to
the front, the front position is 1. If found, returns the position of that item, if not found, returns -1, if the
Queue is empty, returns null.

Figure 16: search of Queue

Application to Scenario: Use search function to find the customer named "Trong" closest to the first
customer, so there are 2 customers named "Trong" but the function returns the position closest to the
front as 2.
5. Sorting algorithms
a. Introduction
Sorting is an operation that puts data in the proper order. Widely used in practical problems, important
in data analysis and data query.
Sorting algorithm is an algorithm that puts the elements of a list in an ascending or descending order,
etc. In other words, a sorting algorithm is used to reorder a certain array. or enumerate the elements by
a comparison operator on the elements. The comparison operator is used to decide the new order of the
elements in the corresponding data structure.
Example: sorting 6,7,3,5,2,9 => 2,3,5,6,7,9 or 9,7,6,5,3,2
Sorting algorithms are classified according to methods such as stability (stable or unstable),
compatibility (incompatible or compatible), etc.
Some sorting algorithms like selection sort, bubble sort, quick sort, counting sort, tim sort, etc.
In the next section, selection sort and quick sort will be introduced.
The selection sort algorithm is a popular algorithm with the use of two loops, often applied to sorting
problems with a small number of elements. It has the advantage of being simple, easy to use, just passing
10



a list of elements, does not generate too much memory because it does not create new arrays. Very good
performance for lists with not too large number of elements. However, it also has a lot of disadvantages,
that is, using 2 loops will increase the time complexity, when the number of elements is large, the time
also increases exponentially. Therefore, it should only be applied to small-range sorting problems. Also,
it cannot keep the original list.
Quick sort is a good sorting algorithm that can be used for large problems because it is an in-place sort
algorithm, using divide-and-conquer and recursive methods, without generating new lists, numbers. the
number of memory cells is not too large, the time complexity is quite small. However, in some special
cases, the time complexity can be the same as selection sort, so it should be based on the appropriate use
case. Like Selection sort, quick sort cannot preserve the original list.
b. Selection sort
 Step:
Array a with n elements, sorted in ascending order.
Step 1: Call out the element with index = 0
Step 2: Assign min = index
Step 3: Compare in turn the array condition at position > array at position from index + 1 to n - 1.
Step 4: If the array at min is different from the array at index, then permute them.
Step 5: If index < n -2 then index = index + 1 and go back to step 2.
 Pseudocode of selection sort
Array A[n]
For i = 0 to n-2 do:
min = i
For j =i + 1 to n-1 do:
If A(min) > A(j)
min = j
End-If
End-For
If min != j

Temp = A(min)
A(min) = A(i)
A(i) = Temp
End-If
End-For

11




Flowchart

Figure 17: Flowchart of selection sort



Example

Array has 4 element {9,5,11,2}

Figure 18: Example of selection sort (1)

At i = 0, min = 0:
j = 1: 9 > 5 => min = j = 1
j = 2: 5 < 11
12


j = 3: 5 > 2 => min = j = 3

min != i => swap => {2,5,11,9}

Figure 19: Example of selection sort (2)

At i = 1, min = 1:
j = 2: 5 < 11
j = 3: 5 < 9

Figure 20: Example of selection sort (3)

At i = 2, min = 2:
j = 3: 11 > 9 => min = j = 3
min != i => swap => {2,5,11,9}

Figure 21: Example of selection sort (4)



Implementation

Data structure is used: Integer array has n elements, loop for.
Time complexity: The first loop always runs through (n-1) elements, the second loop always runs
through (n-i-1) elements. Hence, time complexity is O(n2).
Space complexity: The generated memory consists of int variables like min, i, j, temp, occupying
constant memory so the space complexity is O(1).
Source code:
13


Figure 22: Source code of selection sort


c. Quick sort
 Step:
Given array of type Integer with n elements, n > 0.
Rules for choosing pivot variables: The pivot variable is the axis of the array, it is the value in the
middle of the array. The pivot index is calculated using the formula: first index + (last index - first
index)/2.
Quick sort algorithm: The principle of quick sort is to sort elements that are smaller than the pivot
before the pivot and larger than the pivot after the pivot. In most cases, quick sort will split the list
into small lists to sort until the sublists have only 1 element left, then quick sort is complete.
Pass in 2 parameters, the first index (0) and the last index (length - 1) of the array.
Step 1: Assign the first and last index to two variables i and j, respectively. Use those two variables
to find the pivot.
Step 2: Compare i <= j, if true go to step 3, if false go to step 6.
Step 3: Compare the array at position i >= pivot, if false, increase i value by 1 and repeat step 3, if
true go to step 4.
Step 4: Compare the array at position j <= pivot, if false, reduce the value of j by 1 and repeat step
4, if true, go to step 5.

14


Step 5: Compare i <= j, if false, return to step 2. If true, permute the two elements at i and j together,
then increase i by 1, decrease j by 1, go back to step 2.
Step 6: Compare the first index < j, if true, recursively perform quicksort with 2 parameters,
respectively, the first index and j. If it is wrong, go to step 7.
Step 7: Compare last index > i, if true, recursively perform quicksort with 2 parameters i and last
index respectively. After the execution is done or the condition is false, the quick sort ends.



Pseudocode of Quick sort
array[end + 1]
quick(start, end)
i = start
j = end
pivot = array[start + (end - start)/2]
While i <= j do:
While array[i] < pivot do: i = i + 1
End-While
While array[j] > pivot do: j = j - 1
End-While
If i <= j
temp = array(i)
array(i) = array(j)
array(j) = temp
i=i+1
j=j-1
End-If
If start < j
quick(start, j)
End-If
If end > i
quick(i, end)
End-If

15


End-While




Flowchart

Figure 23: Flowchart main of quick sorting

Figure 24: Flowchart quick function

16



×