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

ASM 1 Algorithm and Datastructure FPT GREENWICH BTECH Distinction(SUPER HOT SALE)

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.62 MB, 31 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

26/02/2022

Date Received 1st submission

Re-submission Date

Date Received 2nd submission

Student Name

Student ID

Class

Assessor name

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:


Table of Contents
B.
CREATE A DESIGN SPECIFICATION FOR DATA STRUCTURES EXPLAINING THE VALID OPERATIONS
THAT CAN BE CARRIED OUT ON THE STRUCTURES ........................................................................................ 6
1.

Abstract Data Types ............................................................................................................................ 6

2.

Stack Abstract Data Type..................................................................................................................... 6
a) Definition: Stack ADT could be simply understood as a linear data structure utilized for storing
data (quite similar to Linked Lists). In other words, the stack can also be viewed as an order list.
Hence, the order where the data is stored as well as retrieved very matters in the stack. Basically,
the final element added also is the first element which is removed from the stack. LIFO(Last in first
out) or FILO(first in last out) list are the other names of stack ADT because of the stack’s mechanism.
6
b)

Stack operations and working mechanism:..................................................................................... 7

c)

Applications/Examples of Stack ....................................................................................................... 9

C.
DETERMINE THE OPERATIONS OF A MEMORY STACK AND HOW IT IS USED TO IMPLEMENT

FUNCTION CALLS IN A COMPUTER............................................................................................................... 10
1.

Definition of Stack Memory .............................................................................................................. 10

2.

Operations of Stack Memory ............................................................................................................ 10

3.

How it is used to implement function calls in a computer ............................................................... 10

D.

Queue ADT (FIFO) .............................................................................................................................. 13
1)

Definition: .......................................................................................................................................... 13

2)

Queue operations and working mechanism ..................................................................................... 13
a)

Main operations: ........................................................................................................................... 13

b)

Other operations: .......................................................................................................................... 14


3)
E.

Applications/Examples of Queue ...................................................................................................... 15
Compare the performance of two sorting algorithms.......................................................................... 16

1.

Introduction ....................................................................................................................................... 16
a)

Definition: ...................................................................................................................................... 16

b)

Some common sorting algorithms: ............................................................................................... 16

c)

Chosen Sorting Algorithms: ........................................................................................................... 16

2.

Bubble Sort: ....................................................................................................................................... 18

3.

Quick sort: ......................................................................................................................................... 21



F.

USING AN IMPERATIVE DEFINITION, SPECIFY THE ABSTRACT DATA TYPE FOR A SOFTWARE STACK .. 24
1.

Explanation of how to specify an abstract data type using the example of the software stack ...... 24
1.1.

Introduction to the formal specification, types of formal specification languages .................. 24

1.2.

Describe what are Pre-condition, Post-condition and error-condition ..................................... 25

2.

Explanation Of The Advantages Of Encapsulation And Information Hiding When Using An ADT ... 28
a)

What is encapsulation ................................................................................................................... 28

b)

Why do we need encapsulation? .................................................................................................. 28

c) Advantages of encapsulation and information hiding when using an ADT Encapsulation uses
accessors and mutators Encapsulation uses properties ....................................................................... 29
d)
G.


Read-only property and Write-only property ............................................................................... 30
CONCLUSION ..................................................................................................................................... 30

References .................................................................................................................................................... 30

List of figure
Figure 1: Stack ............................................................................................................................................................... 6
Figure 2: Push operation illustration ............................................................................................................................ 7
Figure 3: stack overflow ................................................................................................................................................ 7
Figure 4: Pop operation illustration .............................................................................................................................. 7
Figure 5: PeekTop Opeartion Illustration...................................................................................................................... 8
Figure 6: isEmpty operation illustration ....................................................................................................................... 8
Figure 7: Example of Stack(1) ....................................................................................................................................... 9
Figure 8: Example of Stack(2) ....................................................................................................................................... 9
Figure 9: Example of Stack(3) ....................................................................................................................................... 9
Figure 10: Example of Stack(4) ..................................................................................................................................... 9
Figure 11: Code Example ............................................................................................................................................ 11
Figure 12: Function call examples............................................................................................................................... 13
Figure 13: EnQueue Illustration .................................................................................................................................. 13
Figure 14: DeQueue Illustration.................................................................................................................................. 14
Figure 15: PeekHead illustration................................................................................................................................. 14
Figure 16: QueueSize operation ................................................................................................................................. 14
Figure 17: isEmptyQueue illustration ......................................................................................................................... 15
Figure 18: Sorting algorithm ....................................................................................................................................... 16
Figure 19: Bubble sort flow chart ............................................................................................................................... 20
Figure 20: Bubble sort Source code ............................................................................................................................ 20
Figure 21: Bubble sort example .................................................................................................................................. 21
Figure 22: Quick Sort Flow chart ................................................................................................................................. 23



Figure 23: Quick Sort Code implementation .............................................................................................................. 23
Figure 24: Quick sort example .................................................................................................................................... 24
Figure 25: Encapsulation Illustration .......................................................................................................................... 28

A. INTRODUCTION
In this assignment, there are some tasks I need to complete such as creating a design specification for
a data structure that consists the valid operations. Following that, I will demonstrate memory stack
operations and how they are applied in computers to handle function calls. Additionally, I will describe
the abstract data type for a software stack using an imperative description. To more specific, taking an
example to introduce the concept of data structure for a First In First Out (FIFO) queue. The
performance of two sorting algorithms will next be compared and discussed: bubble sort and quick
sort. In the end, discussing about the benefits of encapsulating and concealing data with ADT.


B. CREATE A DESIGN SPECIFICATION FOR DATA STRUCTURES EXPLAINING THE VALID OPERATIONS THAT CAN
BE CARRIED OUT ON THE STRUCTURES
1. Abstract Data Types
Definition: Basically, Abstract Data Type(ADT) is viewed as an abstraction of data structure, where only
operations are defined but do not show their actual implementation. Specifically, It is not specified
what algorithms will be utilized to implement the operations or how the data will be arranged, retrieved
or stored in memory (Karumanchi, 2017).
Because it provides an implementation-independent perspective, it is considered "abstract."
Abstraction is the process of presenting only the necessary information while obscuring the subtleties.
Each abstract data type always consists of the data collection and some operations on the data or
nested data.
Typically, to make an ADT, this is essential to have a set of activity axioms that govern the interaction
of operations. Here are some common types of axiomatic operations of a basic ADT:
creators(constructor), producers(+,-,*,/ decrease size when deleting element), accessors and mutators.
Some ADTs which are commonly used are List, Stack and Queue and here are a summary of their

accessors and mutators operations:
Stack
Queue
List
Mutators

Push()
Pop()

EnQueue()
DeQueue()

Accessors

PeekTop()
isEmpty()
Size()

PeekHead()
isEmpty()
Size()

Insert()
Remove()
RemoveAt()
Replace()
Get()
Size()
isEmpty()
isFull()


These operations provide for them(List, Stack, Queue) the ability to interact with the data of its
instances. The term in the operation’s name also shows the clear purpose and logical behaviour of each
one.
2. Stack Abstract Data Type
a) Definition: Stack ADT could be simply understood as a linear data
structure utilized for storing data (quite similar to Linked Lists). In
other words, the stack can also be viewed as an order list. Hence, the
order where the data is stored as well as retrieved very matters in
the stack. Basically, the final element added also is the first element
which is removed from the stack. LIFO(Last in first out) or FILO(first
in last out) list are the other names of stack ADT because of the
stack’s mechanism.

Figure 1: Stack


b) Stack operations and working mechanism:
Some particular operation terms are given to the two changes that can be made to a stack. For
simplicity, assume the data parameter is the integer data type:
 Push(int):
When an element is added to the top of a stack, this operation is called “push”.

Figure 2: Push operation
illustration

 The “push” operation inserts and stores the element parameter onto the
top of the stack.
 Each stack also has a fixed capacity; hence, the operation “push” could be
performed if the stack is not full. In case the stack is full and the push

operation is still called to insert an element, this causes stack overflow and
the mechanism of push operation will throw a “stack overflow error”
exception.
 When pushing an element successfully, the push mechanism returns the
value of the inserted element.

Figure 3: stack overflow

 Int Pop():
 When an element on the top is deleted from the stack, this operation is called “pop”.

Figure 4: Pop operation illustration


 The “pop” operation removes and returns the current last(top) element(or the element
which is most recently added) in the stack. This working mechanism implicitly describes the
order of the element in/out(the last inserted element is also the first removed element).
 If the stack is empty but the “pop” method is still called, this will cause stack underflow.
When this case happens, the underflow condition of the “pop” method will immediately
throw “nullpointerexception” or other “RuntimeException”.
 “pop” operation returns the integer value of the removed element.
 Int PeekTop():
 The “PeekTop” operation retrieves and returns the top(last) integer element in the stack
without deleting this one like the “pop” operation.

Figure 5: PeekTop Opeartion Illustration

 As the “Pop” operation, If the stack is empty but the “PeekTop” method is still called, this
will cause stack underflow. When this case happens, the underflow condition of the
“PeekTop” method will immediately throw “nullpointerexception” or other

“RuntimeException”.
 Boolean isEmpty():
 When other operations (“pop”, “peek top”,…) always need to check the number of existing
elements in the stack(empty or not) to decide to perform algorithms or throw an error.
“isEmpty” will be in charge of this task.

Figure 6: isEmpty operation illustration


 “isEmpty” will check the existence of the top(last) element in the stack. If this element does
not exist, “isEmpty” returns true and reverse.
c) Applications/Examples of Stack
 One of the applications widely known is Undo
sequence in a text editor(word, excel, notebook, etc…).
Based on the stack mechanism, the last text or
sequence users delete or change is also the first one
which will be “undo”(or restored) in the text editor.
Figure 7: Example of Stack(1)

 The other significant example of the stack that anyone who
knows the internet sees or uses at least one time is “Page-visited
history in a Web browser [Back Buttons]”. Simply, the last
page(website, site) users access is the first one which will be
redirected to when users click the “Back button” on the
browser. Additionally, the way the history of the web browser
stores the list of website users’ access also is one example of the
stack. The last website user’s access is always pushed to the top
of the history list sequentially.

Figure 8: Example of Stack(2)


 Different types of parenthesis are used in programming, such as - (,),
and, to open and close blocks of code (Jaswal, 2020). This parenthesis
then influences how our program runs by being stored in the stack.
Figure 9: Example of Stack(3)

 Stack memory – the base concept of computer science is also one of the
examples. Different from Heap memory, stack memory stores the local
variables of each method when it is executed in the order of the Stack
ADT (last in first out) in temporary memory(RAM). The last function data
store also is the first one which will be removed.

Figure 10: Example of Stack(4)


C. DETERMINE THE OPERATIONS OF A MEMORY STACK AND HOW IT IS USED TO IMPLEMENT FUNCTION
CALLS IN A COMPUTER
1. Definition of Stack Memory
The execution of a thread using Stack memory. Stack memory mainly stores the function calls, primitive
local variables and references to other objects in the heap that the method is referring to as well as
temporary method-specific variables. Stack is one of the significant stack ADT applications, it always
refers to storing data in LIFO(last in first out) order (Kamil, 2019).
To store local primitive values and references to other objects(such as an array, String,…) in the
function calls, a new stack frame is always created for each method call in the stack memory. When
the function call is complete, the stack frame is popped out and terminated. The size of each stack is
limited based on OS.
2.

Operations of Stack Memory
Because the data is inserted and deleted in a last-in-first-out manner based on function call, It has two

principal operations:
 Push: Storing the new data onto the top of stack memory.
 Pop: Restoring the last data on the top of stack memory.
 Peek: Access and retrieve the last data on the top of stack memory.

3.

How it is used to implement function calls in a computer
Before talking about the implementation of function calls, there is a concept needing to be defined
and this is the activation record. An activation record, which contains the space for all of the function's
parameters and local variables, temporary objects, the return address, and other things the function
needs, is where most implementations keep the data for a function call as a whole (Kamil, 2019).
When a function is called, the activation record is created immediately and the stack memory
mechanism will push it to the top of the stack in this thread(Pushing). In this case, the activation record
now could be called the stack frame(or block; in other words, the stack frame is an implementation of
the activation record). The first activation record(stack frame) to be terminated is the most recent one
that has been created.
For more specific, there is a particular example of the function call:


I have a code screen like this one:

Figure 11: Code Example

Here are the illustration of stack memory and their explanations.
Illustration
Explain
When running the program, the main() function is called first, hence an
activation record(stack frame) is created and pushed to the top of the
stack.

The variable reqCapital(primitive type) is stored in this stack frame space
with the value 1000

In the main() function, it calls the getCapital() function; so, the new
unique stack frame is created and pushed on top of the previous stack
frame.
The parameter c is stored temporarily in this stack frame space.


In the getCapital(), when the bribeBoss() is called, new stack frame
immediately is created and pushed on top of stack.
This stack frame store the argument (int m = 1000) passed from
getCapital() function and the variable bribeMoney(int) = 300 after
calculating.

When the bribeBoss() function finishes executing, this stack frame will
be popped out from the stack and all data stored in this one also are
terminated from memory. This function return the value to the
getCapital() function and that value replaces the function call in the the
stack frame of getCapital() function.

The stack frame of getCapital() is popped out when this function is
completed. All data stored in getCapital() stack frame also are
terminated. Only the return value is returned to main() function and the
main() function stores it temporarily.

When the program finishes, all stack frames are popped out.


Summary of the working process of how the stack memory implements function calls:


Figure 12: Function call examples

D. Queue ADT (FIFO)
1) Definition:
The queue is a common abstract data type used to store data in an order list in which the data is
inserted at the end of the queue and removed in the first place of this one. In other words, the first
data inserted is the first one which will be removed from the queue. Hence, its mechanism is called
FIFO(first in first out) or LILO(last in last out).
2) Queue operations and working mechanism
Based on queue mechanism(FIFO), here are some specific operation terms making a queue ADT. For
simplicity, assume the data parameter is the integer data type:
a) Main operations:
 EnQueue: when one element is added to the queue, this operation is called “EnQueue”.

Figure 13: EnQueue Illustration

EnQueue gets the parameter’s value and inserts it in the end sequently with each inserted
element.
Each Queue also has a fixed capacity; hence, the operation “EnQueue” could be performed if
the queue is not full yet. If the queue does not have any available place and the enqueue
operation is still called to insert an element, this causes queue overflow and the program of
enqueue operation will throw a “queue overflow error” exception.


 DeQueue: When the element is removed from the queue, this operation is called “DeQueue”

Figure 14: DeQueue Illustration

DeQueue removes the first element(which has been first inserted into the queue. In other

words, the located at the first place in the queue) sequently with each inserted element.
This operation only is used when the Queue has at least one element; In other words, when
the queue is not empty, DeQueue could be executed. If the queue does not have any element
(empty queue) and the dequeue operation is still called to delete the first element, this causes
queue underflow and the program of the dequeue operation will throw a “queue underflow
error” exception.
When the Dequeue completes deleting the first element, it will return this value of this
element.
b) Other operations:
 PeekHead: This operation also returns the first element without deleting it.

Figure 15: PeekHead illustration

As the “DeQUeue” operation, If the queue is empty but the “PeekHead” method is still called,
this will cause queue underflow. When this case happens, the underflow condition of the
“PeekHead” method will immediately throw “nullpointerexception” or other
“RuntimeException”.
 QueueSize: QueueSize returns the existed number in queue.

Figure 16: QueueSize operation


 isEmptyQueue: When other operations (“Dequeue”, “peek head”,…) always need to check the
number of existing elements in the queue(empty or not) to decide to perform algorithms or
throw an error. “isEmptyQueue” will be in charge of this task.

Figure 17: isEmptyQueue illustration

This operation will return true if the queue is empty and reverse.
3) Applications/Examples of Queue

a) Task Queue in javascript: the concept “event loop” in javascript contains two more sub-concepts:
Microtask Queue and Macrotask Queue which are the significant application of Queue ADT. These
names of this two-term (microtask “Queue” and macrotask “queue”), explicitly show that they are
based on the Queue mechanism (FiFo or first in first out). Specifically, The event loop takes and
deletes the first task at the first place in the micro-macro task queue, and when another asyncrinous
task is performed, this will be added at the end of these task queues after some handling process.
b) Another application of Queue is Access to Shared Resources. In a networked system, several
workstations or computers request a service from a single resource at the same time. The queries
are processed in fractions of a second, which is extremely quick (Anon., 2021).
Despite the fact that there is usually some time gap in the requests generated. This state is kept by
implementing a queue in the server's device.
c) Job Scheduling: CPU scheduling or I/O scheduling or Job scheduling is the most essential application
of a queue. A queue ADT is used to organize and schedule the jobs that computers do in the
processor/CPU. That is the way the computer does these jobs in the sequence stipulated (Pandey,
2022).
d) Message/mail queue: A queue is a line of messages that are waiting to be treated, commencing at
the top and working down the line. A message queue is a collection of messages that are transferred
from one application to the next. It holds a collection of work objects that are awaiting processing.
A message is data that is sent between the sender and recipient programs; it is just a byte array
with some headers on top. One form of the message is an event. One program directs another
application to begin processing a given job by using the queue.


E. Compare the performance of two sorting algorithms.
1. Introduction
a) Definition:
A sorting algorithm performs the sorting on all components of a list(array,..) in a certain order,
either in ascending or descending order. In other words, the actual output after applying the sorting
algorithm is the permutations or reorderings of the input in a certain order (Karumanchi, 2017).


Figure 18: Sorting algorithm

The necessary of the sorting algorithms:
Sorting is viewed as one of the essential types of algorithms in computer science. The sorting
algorithm can appreciably lower the complexity of a problem(such as sorting before performing a
searching algorithm will reduce the time complexity) and is often used for database algorithms and
searches.
b) Some common sorting algorithms:
Here are some sorting algorithms that can be introduced such as Selection Sort, Bubble Sort,
Insertion Sort, Quick Sort, Merge Sort, and Heap Sort,…. However, this report just dives into two
sorting algorithms and they are Bubble Sort and Quick Sort.
c) Chosen Sorting Algorithms:
The reason why they are chosen:
Bubble Sort and Quick Sort are chosen for diving into the concepts of sorting algorithms because
they are viewed as the representation of the simple and complex levels of the sorting algorithm.
Bubble sort is the simplest sorting algorithm, its mechanism(including compare, swap, and
iteration) indicates the basic foundation and the base logic of all other sorting algorithms. This one
also is the best practice for everyone who wants to start learning sorting algorithms.


Quick sort is the representative sorting algorithm that applies the divide-and-conquer algorithmic
technique. It also is the sorting algorithm that gets most widely used in many programs. Its
partitioning mechanism brings about parallelizable logic.
Compare the chosen sorting algorithms:
 Bubble sort:
The list(or array,…) is traversed repeatedly until this one is sorted. The name of the comparison
sort method refers to pushing the "bubble" of smaller or bigger entries to the end of the list
(Toscano, 2015). The algorithm repeats comparing each couple of elements and swapping them
if they are not in a certain order until it can traverse the complete collection without discovering
any components that need switching places.

Performance:
 In case the list is already sorted in a certain order(ascending or descending) with a small
number of elements, bubble sort will examine that in the initial loop that no couple of
elements need to be swapped and will then terminate immediately. Because it just needs
to perform n-1 comparisons; therefore, the complexity now is O(n) and this also is the best
case.
 Except for the above case, other cases such as the list is not already sorted or the huge
amount of elements in the list(or array) also bring about Bubble sort the bad case than the
average case with time complexity is O(n2).
Here is the summary of Bubble sort complexity:
Worst case complexity: O(n2)
Best case complexity: O(n)
Average case complexity: O(n2)
Worst case space complexity: O(1) auxiliary
Advantages of Bubble sort:
 This is the basic and simplest algorithm, which is very suitable for newbies with the sorting
algorithm.
 Easy and straightforward to implement with a short structure.
Disadvantages of Bubble sort:
 Worst performance when compared with other sorting algorithms.
 Really bad handling with a large amount of data in a collection.
 Quick sort
By dividing the input into two parts by choosing pivot, sorting them, and then recombining
them, Quick sort is implied that each iteration operates in this manner (Patel, 2019).


Performance:
 Best Case Complexity: The best case occurs when the pivot element chosen by the
partitioning method is always in the middle or close to the middle element. The fastest
possible sorting time is O (n*log(n)).

 Average Case Complexity: When the array components are in a disorganized sequence.
O(n*log(n)) is the average case time complexity of Quicksort.
 The worst-case scenario for complexity is when the partitioning algorithm consistently
chooses the largest or smallest member as the pivot element. Quicksort's worst-case
temporal complexity is O(n2).
Advantages of Quick sort:
 It operates quickly and efficiently.
 Among various sorting algorithms, it has the lowest temporal complexity.
 Quick sort is a great option when space is restricted because of its O(log(n)) space
complexity.
Disadvantages of Quick sort:
 This sorting method is regarded as unstable since it does not preserve the original order of
the key-value pairs.
 When the pivot element is the biggest or the smallest, or when the sizes of all the parts are
the same. These worst-case circumstances drastically reduce the quicksort's performance.
 As a recursive process, it is challenging to implement, especially if recursion is not possible.
2. Bubble Sort:
 Bubble Sort implemented Step by Step:
 This algorithm iterates via elements by using for loop.
 Starting with the first element(index = 0), continue the next for loop inside the first one and
also start with index = 0. Each iterating time of the nested loop performs comparing of the
current element with the next element of the array sequentially.
 Based on the sorting of a certain order. If the current element is bigger or smaller than the
next element of the array, swap them.
 If the current element is meet the type of sorting order when compared with the next element,
move to the next element.
 After each time the first loop run the biggest or smallest element will be located at the end of
the list(or array,..).
For more specific, here are pseudocode, flowchart and code implementation of bubble sort:



Pseudocode:
Public void bubleSort(list / array of items )
//this algorithm is declared as a function
n = array.length;
for i = 0 to loop-1 do:
flag = false
//flag is understood as a checker to somehow get the best case of bubble sort as well as
enhance its performance.
for j = 0 to loop-1 do:
if array[j] > array[j+1] then
// compare the contiguous elements
swap( list[j], list[j+1] )
// swap them
flag = true // flag is true informing that this loop time has performed the swap
end if
end for
if(flag is false) then
break
// if no number was swapped that means the array is sorted now, break the loop. If just
after one loop and flag is still false, it provides the best case of bubble sort
end if
end for
end void


Flowchart of Bubble sort:

Figure 19: Bubble sort flow chart


Code implementation(Java):
To implement this algorithm as a function, the argument of this function now is integer data type:

Figure 20: Bubble sort Source code


 Example:
For illustration, I apply the bubble sort algorithm to a simple array which is not sorted yet. Here is
this array: {6,9,3,4} and this array will be sorted in descending order. Specifically, this sorting
process will be described with images.
Explain
 In the first time iteration of two loops,
starting from the first index(j/0), the
program compares the j index and the
j+1 index. Because it sort in descending
order, 9 is greater than 6 the program
swaps them to meet the condition.
 The second time iteration of the nested
loop, continues to compare the 6(j index)
and 3(j+1) index because 3 is already less
than 6 and located after, there is no
swap.
 Next, it continues to compare 3(j) and
4(j+1 index). The 4 is greater than 3, the
program swaps them.
 Now the first nested loop is completed in
looping through all the element, the Figure 21: Bubble sort example
outside loop increase the i variable and
the next time loop will continue.
 However, the array now is already

sorted, the flag will still be false and it
meets the condition (flag == false) the
loop break and the algorithm also
finishes with the sorted array.
3. Quick sort:
Quick sort implemented step by step:
 Picking the pivot. The pivot could be the first or last or even the middle element, picking the pivot
is determining mostly the time complexity of this algorithm.
 Set two variables to point left and right(first and last element) of the array except for the picked
pivot.
 If the value of the element is greater than the pivot, move it to the right side of the pivot or keep
it in the original location if it’s already located on the right side of the pivot.
 If the value of the element is less than the pivot, move it to the left side of the pivot or keep it in
the original location if it’s already located on the left side of the pivot.
 Swap left and right.
 if left ≥ right, the point where they met is the new pivot.


For more specific, here are pseudocode, flow chart and code implementation of Quick sort:
Pseudocode: For best practice, the quick sort algorithm is divided into three parts:
//left –> Starting index, right–> Ending index of array
quickSort(arr[], left , right)
if left < right then
pivot = partition(arr, left , right)//pivot is partitioning index, arr[pivot] is now at right place
quickSort(arr, left , pi – 1) // Before pivot
quickSort(arr, pi + 1, right) // After pivot
end if
// my way is picking the last element as the pivot, placing the pivot at its accurate position in the
sorted array, and placing all smaller elements to the left of the pivot and all greater elements to the
right of the pivot

partition (arr[], left, right)
pivot = arr[right]; //pick the last element of the array to be the pivot
j = (left– 1) // Index of the -1 element and implicitly indicates the right position of the pivot
for (i = left; i <= right- i; j++) do :
if (arr[i] < pivot) then // If the current element is smaller than the pivot
// increase the index of the smaller element by one digit
swap arr[i] and arr[++j] // swap them
end if
end fo
swap arr[++j] and arr[right]) // bring pivot to the accurate location
return j
Swap(arr[], curr, other) // this function only do swap
Temp = arr[curr]
Arr[curr] = arr[other]
Arr[other] = temp


Flow chart:

Figure 22: Quick Sort Flow chart

Code Implemetation:
To implement this algorithm as a function, the argument of this function now is integer data type

Figure 23: Quick Sort Code implementation


 Example:
For instance, I apply quick sort on a simple array {3,7,6,4,5}. This array will be sorted in ascending
order.

Explain
 Firstly, the last index element is chosen
to be the pivot. The program will
compare the first index and the pivot. If
the first index element is less than the
pivot, the j index will be increased and
swapped with the first index element.
In this case, the first index == the ++j
index, 3 is still in this place.
 The program continues to compare
sequentially with the next index
element 7, it is greater than 5, there is Figure 24: Quick sort example
no change or swap.
 The next number is 6 and it’s greater
than the pivot, there is no change or
swap. The next element is 4 and it is
less than the pivot. Now, j is increased
and the element at the j index (7) is
swapped with the current index
element(4).
 Now, the first partition is done and the
program continues executing recursion
to keep partiting. However, the array
now is sorted and the condition of the
program will automatically terminate
the quicksort with the sorted array.
F. USING AN IMPERATIVE DEFINITION, SPECIFY THE ABSTRACT DATA TYPE FOR A SOFTWARE STACK
1. Explanation of how to specify an abstract data type using the example of the software stack
1.1. Introduction to the formal specification, types of formal specification languages
a) Introduction to the formal specification:

In software engineering, highly comprehensive descriptions are referred to as 'formal
specifications' (Nissanke, 2012). Formal specifications are also a method of communication,
therefore they must be clear and short their vocabulary, syntax, and semantics are formally
defined.
In other words, formal specification is the translation of a non-mathematical clarification
(diagrams, tables, English text) into a formal specification language with a brief explanation of
the high-level behaviour and properties of a system. They must utilize an agreed-upon language


that everyone uses and understands. It’s used to describe external behaviour without describing
or constraining the implementation of software.
b) Types of formal specification languages
 Axiomatic Specifications
Use a number of stateless functions, each with its own set of pre- and post-conditions. Preand post-conditions are predicates over the inputs and outputs of a function. A predicate
is a true or false Boolean statement with variables that are the parameters of the function
being stated.
Stages of axiomatic specification of a function:
 Determine the range of input parameters across which the function is expected to
perform successfully. As a condition, provide the constraints on the input
parameters.
 Define a predicate that defines a condition that must hold on the function's output
if it operates appropriately.
 Determine what modifications (if any) are made to the function's input/output
parameters. (Note: no parameters would be updated in a strictly mathematical
function. However, some programming languages alter parameters through a call
by name or call by reference.)
 Combine these into pre- and post-conditions for the function.
 VDM
VDM is an abbreviation for "The Vienna Development Method," which is a set of
methodologies for the formal specification and development of computing systems

(Fuchs, 1992). It consists of a specification language called VDM-SL; rules for data and
operation refinement that allow one to establish links between abstract requirements
specifications and detailed design specifications down to the level of code; and a proof
theory in which rigorous arguments about the properties of specified systems and the
correctness of design decisions can be conducted.
1.2. Describe what are Pre-condition, Post-condition and error-condition
a) Pre-condition: A precondition could be understood as a condition that determines what has to
be true and after that, the operation could be executed. In other words, the operation could
not be executed in case the precondition is false. The precondition commonly represents the
expectation of the operation’s argument or the state of objects that the operation may use.
b) Post-condition: Like a precondition, a postcondition also is a condition but this one determines
what would be true when the operation completes this task. Simply put, when the precondition
is true and the operation completes the task, the postcondition is ensured to be true.


×