0% found this document useful (0 votes)
114 views118 pages

PArkash DAta Structure

This document discusses various data structures and algorithms. It begins by defining different types of data structures like arrays, linked lists, stacks, and queues. It then provides examples of these structures for an online shopping system. Next, it explains how memory stacks are used to implement function calls in computers using the LIFO principle. The document also illustrates a queue data structure for a FIFO system. It compares the performance of insertion sort and selection sort algorithms. Finally, it analyzes the Dijkstra's and Floyd-Warshall shortest path algorithms through examples and comparison. The document thus provides specifications and examples of commonly used data structures and algorithms.

Uploaded by

Raisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
114 views118 pages

PArkash DAta Structure

This document discusses various data structures and algorithms. It begins by defining different types of data structures like arrays, linked lists, stacks, and queues. It then provides examples of these structures for an online shopping system. Next, it explains how memory stacks are used to implement function calls in computers using the LIFO principle. The document also illustrates a queue data structure for a FIFO system. It compares the performance of insertion sort and selection sort algorithms. Finally, it analyzes the Dijkstra's and Floyd-Warshall shortest path algorithms through examples and comparison. The document thus provides specifications and examples of commonly used data structures and algorithms.

Uploaded by

Raisha
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 118

1/1/2020 Data Structure &

Algorithm

BTEC HND in Computing/ Third Semester)


Data Structure & Algorithm 2020

Table of Conten
Part 1:.....................................................................................................................................................4

P1 Create a design specification for data structures explaining the valid operations that can be carried
out on the structures...............................................................................................................................5

Introduction............................................................................................................................................5

Data Structures:.......................................................................................................................6

 Types of data structures...........................................................................................................8

a. Array.........................................................................................................................................10

b. Linked List...............................................................................................................................11

a. Linear........................................................................................................................................11

b. Non-linear................................................................................................................................12

 Advantages of data structure.................................................................................................13

 Disadvantages of data structure.............................................................................................13

Create a design specification for Shop-Now online Shopping Management System......................15

Linked List:..................................................................................................................................17

Stack.............................................................................................................................................46

Implementation of Stack...................................................................................................................47

P2 Determine the operations of a memory stack and how it is used to implement function calls in a
computer...............................................................................................................................................61

Stack memory.......................................................................................................................................61

Basic operations in stack data structure...............................................................................................61

LIFO (Last In First Out).......................................................................................................................62

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

Stack memory in computers.........................................................................................................63

M1 Illustrate, with an example, a concrete data structure for a FIFO queue.......................................69

First in First out (FIFO) Queue:.....................................................................................69

 Comparing Stack and Queue and Judgements...................................................................72

(BTEC HND in Computing/ Third Semester)


2
Data Structure & Algorithm 2020

Functionality of queue with different operations (with code):.....................................................73

Queue in merge sort and selection sort for Shop-Now online Ecommerce Company:................81

M3 Compare the performance of two sorting algorithms....................................................................82

Sorting..................................................................................................................................................82

Insertion Sort (elementary sorting algorithms)....................................................................................83

D1 Analyse the operation, using illustrations, of two network shortest path algorithms, providing an
example of each....................................................................................................................................94

Dijkstra’s algorithm:.............................................................................................................................94

Floyd-Warshall Algorithm:..........................................................................................................98

Comparison between Dijkstra’s and Floyd-Warshall algorithm.....................................................101

Conclusion......................................................................................................................................101

Part 2..................................................................................................................................................102

 Using an imperative definition, specify the abstract data type for a software stack.......................102

 Examine the advantages of encapsulation and information hiding when using an ADT................102

 Discuss the view that imperative ADTs are a basis for object orientation and, with justification,
state whether you agree......................................................................................................................102

P3 Using an imperative definition, specify the abstract data type for a software stack.....................102

Writers name:..................................................................................................................................102

Introduction of article:....................................................................................................................102

Introduction:.................................................................................................................................102

Abstract data type (ADT):..................................................................................................................103

Why stack is called ADT?..................................................................................................................104

ADT for software stack:...............................................................................................................105

M2 Examine the advantages of encapsulation and information hiding when using an ADT............107

Definition of Encapsulation:........................................................................................................107

Definition of Data Hiding.............................................................................................................108

 Advantages of encapsulation and information hiding when using an ADT........................109

(BTEC HND in Computing/ Third Semester)


3
Data Structure & Algorithm 2020

D2 Discuss the view that imperative ADTs are a basis for object orientation and, with
justification, state whether you agree.........................................................................................113

Justification “Is an ADT being basic for OOP”.........................................................................115

References..........................................................................................................................................118

Part 1:

(BTEC HND in Computing/ Third Semester)


4
Data Structure & Algorithm 2020

You will need to prepare a written document which demonstrates the followings

● Create a design specification for data structures explaining the valid operations that can be carried
out on the structures and determine the operations of a memory stack and show how it is used to
implement function calls in a computer.

● Illustrates, with an example, a concrete data structure for a First In First out (FIFO) queue and
compare the performance of two sorting algorithms. Further, produce an analysis of the operation of
the two network shortest path algorithms providing an example of each.

P1 Create a design specification for data structures explaining the valid operations that can be
carried out on the structures.

Introduction
As I am one of the software engineers working in this. B2C Pvt Ltd which is a software company
that works on projects based on machine learning, artificial intelligence, IOT(internet of Things) etc.
Now I am assigned the responsibility to prepare document so as to show your company understands
on use of different ADTs, different sorting and searching algorithms, their applications and efficiency
sorting and searching algorithms, their applications and efficiency. . This task describes one of the
data structures, such as a list of links. Next, we briefly analyze the linked list operation that defines
the example. Second, a brief description of the memory stack and other explanations that are asked
for each question. An example will briefly explain the queue and the two classification algorithms.
Finally, we briefly introduce the two shortest route algorithms in the network, such as the Dijkstra
and Bellman Ford algorithms, and compare them after their operation.

(BTEC HND in Computing/ Third Semester)


5
Data Structure & Algorithm 2020

Data Structures:
Data Structure is a concrete implementation of data types. It is possible to analyze the time
complexity and memory of the Data Structure but not from the data type. Data structures can be
implemented in a number of ways and their implementation may vary from language to language.
Data structure is a specific way to organize your data in a computer so that it can be used effectively.
For example, we can store a list of items that have the same data type using a uniform data structure.

At the backbone of every program or piece of software are two entities: data and algorithms.
Algorithm transform data into something a program can effectively use. Beside, data structures are
computer programs that optimize the way that the information management process calculates
information in memory. Data structures often build each other to create new structure and those
structure are applied to a certain data access pattern. Choosing the most efficient data structure for
the job greatly improves algorithms performance, helping to speed up application processing. This
allows computer systems to efficiently manage massive amounts of data within large- scale indexing,
massive databases, and structure data in big data platforms. In other words, data structure would be
that there are basically different ways of sorting data con your computer and this sentence might not
be too clear so let me give you a more concrete example. Let’s say you want to make a system that’s
sort of like Google Maps for your
neighborhood.

Figure: The Maps

You can see in the picture, it includes your Home, Store A, Store B, School and Intersection, the
arrows show that these are one-way streets, there are a lot of one-way streets here and so for example
you can go from Store A to Store B but not these other way around, and all the line that not arrows
show that they are two-way streets and. You already have each place is coordinates. With each
objects, you have latitudes and longitudes stored on your computer like

(BTEC HND in Computing/ Third Semester)


6
Data Structure & Algorithm 2020

You can see from the Figure above, you can tell
that the latitude of Home is forty- nine point two
and the longitude of Home is minus one hundred
twenty-three point four, and so from the Figure 2
like information you can tell where each location is
exactly where each point is exactly, but you can tell
how these locations are connected with streets and
where the street are exactly, so you need to figure a
way to store that information somehow on your
computer and there actually a few different

Figure: The latitudes and the longitudes of each objects.

options for this. One of those options will be to store all possible paths in list like format. So that,
one of those paths will be from Store A to Home and another one will be Home to Store A, and yet
another path will be Store A to Store B and with that method your data might look like the following
table.

From this list in Figure, like information you can tell that as we saw earlier you can go from Home to
Store A and from Store A to Home, and Home to Store B, and so on. But, you cannot go from Store
B to Home, because this is a one- way street and there is no path from Store B to Home in this list.
Thus, that is one option. Another option might be to list each of these place and for each of those
places just list all the places you can go from that place and with that method your data might look
like on the given figure

(BTEC HND in Computing/ Third Semester)


7
Data Structure & Algorithm 2020

Figure: The method of data.

Instead as you can see here, we have table like information again, where on the left hand side we
have all the places listed include, Home, Store A, Store B, School, Intersection, and on the right hand
side for each of those places we all the places you can go from. As a result, from Home you can go to
Store A, Store B and Intersection as you can see here, and form Store A, you can go to Home or
Store B, so these two method are basically two different ways of sorting exactly the same set of data
and as you can see, they have sort of different structures. There are simplified example of what data
structure look like. If you are ready familiar with data structures you might notice that the first
method corresponds to the array or a list data structure and the second method corresponds to the
hash table or hash map data structure.

Figure: The data

(BTEC HND in Computing/ Third Semester)


8
Data Structure & Algorithm 2020

 Types of data structures

Data structures are divided into two categories, includes, Primitive Data and Non-primitive:

1. Primitive Data Structures


These are supported structures at the machine level, which can be used to create non-
primitive data structures. This is indispensable and pure in form. They have predetermined
behavior and specifications. For example: Integer, Float, Character, and Pointer. However,
pointer does not hold a data value, instead, they keep memory addresses of data values. This
is also called the reference data type.

2. Non-Primitive Data Structures


Non-primitive data structures can be implemented without the original data structure.
Although they are also provided by the system themselves, they are data structures of origin
and cannot be formed without using primitive data structures. Non- primitive data structures
are divided into two types: Simple data structures and Compound data structures.

(BTEC HND in Computing/ Third Semester)


9
Data Structure & Algorithm 2020

Figure: Classify the Non-Primitive Data Structures

Simple data structure


Simple data structure build on data types to create higher level data structures. The most
common simple data structures are Array and Linked lists.

a. Array
The array data structure is one of the oldest and most popular data structures. An array of elements
can be values or variables. The structure determines the elements using an index or key, allowing the
data structure to calculate the position of each element. The memory address of the original element
is called the first platform or address. Data elements are indexed and stored sequentially in adjacent
memory.
There are different types of array data structures. In a common example, many databases use one-
dimensional linear arrays that have database records. Arrays can also be multidimensional if they
access elements from more than one index. Arrays are the fundamental structure for many other data
structures including hash tables, queues, stacks, and linked lists.

(BTEC HND in Computing/ Third Semester)


10
Data Structure & Algorithm 2020

b. Linked List
Link list is the second most popular data structure type. It links elements instead of computer
addresses from pointers. While an array of mathematically computes data entries, linked lists store
data items in its own structure. The structure considers each element to be a single object and each
object contains data and references or the address of the next element.
There are three types of linked lists: singly linked where each node stores the next node’s address
and the end address is null, doubly linked where each node stores the previous and next node’s
addresses and the end address is null, and circular linked where each node links to the other in a
circle, and there is no ending null.
Compound data structure
Computing systems combine simple data structures to form compound data structures. Compound
structures may be linear or non-linear.

a. Linear
Linear data structure from sequences
Stack
A stack is a basic linear data structure: a logical entity visualized as a physical stack or object stack.
The data structure inserts and deletes elements at one end of the stack, called vertices. Developers
develop a stack using arrays and linked lists.
A stack in the order in which the computer system performs operations. The order is usually the first
appearance (LIFO). The main activities for the stack include 1) Push, add an item to the stack; and 2)
Pop, remove an item from the stack in reverse order to Push. Stack also returns an isEmpty value: it
means true on an empty stack and deletes false if there is data.

Queue
Instead of the stack LIFO order, the queue data structure places elements in the queue in the order of
First In First Out (FIFO). The insertion process is called Enqueue, which inserts an element into the
back or tail of the queue. The delete procedure is called Dequeue, removing elements from the front
or the beginning of the queue. To move the element that is inserted into the Dequeued queue, the
stack data structure must remove all elements between the new element and the front of the queue.

Think of this structure in line with the printer queue, where print jobs occur in order until they are
printed or canceled. A queue can be built using arrays, linked lists or stacks.

(BTEC HND in Computing/ Third Semester)


11
Data Structure & Algorithm 2020

b. Non-linear
Non-linear structures are multi-leveled and non- sequential

Graph

Graph data structure is a tree that shows the mathematical image of an object placed with
linked pairs. The object points connected together are vertices and links that are edges.

Hash Table
The hash converts the main value range into the index range in an array. The hash table data structure
links each value in an array with a single index that records the point and insertion position of the
value, which speeds up the search and search of data.
Hash collisions are a common occurrence, especially when hashing very large data warehouses. Most
hash tables include collision resolution, often storing key locks /cursors together with their associated
values.

Tree
Tree is a hierarchical data structure, usually constructed in a top-down structure, in which
each node contains a unique value and contains references to child nodes. In any tree, no
node returns to the original or copies a reference.
The top button is called the root. The direct elements below are its children; The same level factor is
a sibling. If there is one level below these children, the buttons above are also parents. Factors that
occur at the bottom of the tree are called leaves.

Figure 6. The example of tree

Trees are hierarchical data structures that help organizations store data.
The purpose of the tree is to store natural hierarchical information, such as the file system. There are
many types of plants. A binary tree is a tree data structure in which each node has no more than two
children, respectively, is called a right child and a left child. Additional structures are binary trees,

(BTEC HND in Computing/ Third Semester)


12
Data Structure & Algorithm 2020

often used to effectively store router tables for highbandwidth routers; or Merkel tree, the hash value
of each subtree in its parent node. Merkel allows databases like NoQuery Apache Cassandra to
effectively verify large data content.

 Advantages of data structure

 Data structures allow the storage of information on hard drives.


 provides a way to manage large datasets such as databases or internet indexing services.
 Is there a need for efficient algorithm design?
 allowing secure storage of information on your computer. This information can then be used
for later use and can be used by various programs. In addition, the information is protected
and should not be lost (especially if it is stored on magnetic tape).
 allowing data to be used and processed on software systems.
 Enables easier data processing.
 Using the internet, we can access data at any time from any connected machine (computer,
laptop, tablet, phone, etc.)

 Disadvantages of data structure

 Only sophisticated users can make changes to the data structure


 Any problem involving the data structure requires the help of a specialist, which is that basic
users cannot help themselves.

Discussing over all the possible data sorting like linked list, array, queue, and stack I have point out
their use and working principal and it is clear that the role of an array is to store a fixed-size
sequential collection of data in programing. But there are 2 bounds that it has:

1. To change the size of an array, you must create a new array with a new changed size then copying
all data from the old array to it.

2. Similar complexity, when an item wants to be inserted into the array, because data in the array are
consecutively next to each other, so inserting required shifting some other data.

To overcome those two limitations, linked structure is a way to solve.

(BTEC HND in Computing/ Third Semester)


13
Data Structure & Algorithm 2020

Unlike array, linked list is one sequential access type. Each node in the linked list that contains
information about the next node, through which we can access to the node we want to find.

Instead of using array for the E-shop online Ecommerce online company. I have suggested them to
use linked list and produce a short example of how we can sort the huge amount of data using linked
list algorithm.

(BTEC HND in Computing/ Third Semester)


14
Data Structure & Algorithm 2020

Create a design specification for Shop-Now online Shopping Management System


In this project, I use linked list for storing data of product.

NodeT<T>

MyCustomerStack<T> MyOrderQueue

MyList<T>List MyListT<T>list
MyList

+NodeT<T>head,tail

MyCustomerStackT<T>List MyOrderQueueT<T>list

MyListT<T>List

(BTEC HND in Computing/ Third Semester)


15
Data Structure & Algorithm 2020

Class NodeT<T>

In Java, generics are included in the concept. "Generics" means parameterized data types.
Parameterized data type is very important in coding because it allows us to create and use a class,
interface, method with many different types of data. With the help of generics, an Linked List object
is created which contains elements of type T. Type <T> is understood as an Object of the Java
runtime. It is a represent of an object will be specified when using.

Node<T> is considered as a node.

+ info: T - object data carried by this node, could be any types.

+ next: My<T> - reference to the next node in the list, or maybe null.

- More information about nodes in Linked List will be provided in section II.1.C

Class MyListT<T>

- This class is implemented as a Linked List Class from scratch in Java. This program does not use
the stuff in the standard library. The point of constructing this class is to understand how things work,
and understanding linked lists through important steps by steps and understanding more complex in
data structures.

- MyListT<T> is a list containing MyT<T> node, a collection of node is stored in this class, it begins
with a head and ends with tail.

Class MyCustomerStackT<T> and MyOrderQueueT<T>

- This class is implemented as a Stack Class and Queue Class from scratch in Java.

Class Product

- Contain information of one Product. It has 5 values:

+ code: string - the code of the product (this should be unique for the product).

+ pro_name: string - the name of the product.

(BTEC HND in Computing/ Third Semester)


16
Data Structure & Algorithm 2020

+ quantity: i nteger - the number of products with the same code in a shop at beginning of a
day.

+ saled: integer - the number of products with the same code, which are saled in the day.
Condition - saled ≤ quantity.

+ price: double - The price of the product.

Class Customer

- Contain information of one Customer. It has 3 values:

+ ccode: string - the code of the customer (this should be unique for the customer).

+ cus_name: string - the name of the customer.

+ phone: string - The phone number of the customer (must contain digits only).

Class Ordering

- Contain information of one Ordering. It has 3 values:

+ pcode (string) - the code of the product to be ordered.

+ ccode (string) - the code of the customer.

+ quantity (integer) - the number of ordered products.

+ total (double) - total value.

Class OrderingList, CustomerList and ProductList

These classes contain main() function to run the application. The research of Searching, Sorting and
Recursion is come from these classes.

Linked List:

A. Definition of Linked List:


- Linked list is a data structure consisting of a set of nodes, where each node that contains a link to
the next node.

- In “Data Structures and Algorithms in Java, Second Edition by Adam Drozdek”, it is defined (the
definition has been edited by this report’s writer):

(BTEC HND in Computing/ Third Semester)


17
Data Structure & Algorithm 2020

“A linked structure is a collection of nodes storing data and links to other nodes. As a linear
data structure, nodes can be located anywhere in memory, each node holds some information and
reference to another node in the list. If a node has a link only to its successor in this sequence, which
means it has only 2 values: data and next node, the list is called a singly linked list”.

A node includes two data fields: data and next node. The data field is used to store information, and
this field is essential. The next field is used to link another node to form a linked list. It can be said
that linked list is the data structure using recursion, because a node of the list has a reference to the
next node. Typically, a node often points to its next one, but it can also point to itself.

Linked list can be considered as one of the sequential arrangement of nodes. Starting with a node as
the first element in the list which called a head, following its link pointing to, we have the second
node which is considered the second element in the list, etc.… continuing so until the end of the list.
The last node can link to a null, which means it does not point to any node, or it may point to the first
node to form a circular linked list.

B. Comparison between Array with Linked List and judgments:


1. Accessing speed (Searchable) and editable:

Array Linked List


The array can be accessed randomly through The list can be only sequential accessed.
the index value.

- Point of view: In linked list, if you want to access to a node, you will have to start from the head
and then access respectively to the next element until you reach the wanted node. It is a complex
process for modifying the node in the list, which means it takes time and slows down the speed of
searching. Unlike linked list, elements can be modified easily by identifying the index value.

2. Changing the position of an element:

Array Linked List

(BTEC HND in Computing/ Third Semester)


18
Data Structure & Algorithm 2020

Array has homogenous values. Each element Each node relates to its previous node, which
is independent of its position. is a pointer to the next node.

- Point of view: Arrangement and ordering elements of a linked list is much simpler than the array.
Because for the linked list, to change the position of an element, we just need to change the
references of elements involved, but in the array, we often change the positions of many elements.

3. Size:

Array Linked List


The size must be declared. The size is unlimited.

- Point of view: Due to the dynamic feature of the linked list, the size of the linked list can be much
more flexible than array. The size of the list does not have to be declared, we can easily create or
delete an element in the list and it will automatically expand or shrink the list. On the other side, the
array is one set with a fixed number of elements, so if it need to be expanded to add new element or
contracted for deleting, it will take an effort to construct some complex algorithms.

C. Implementation of Linked List


In SMS application, singly linked list is implemented like this:

MyList

NODE

(BTEC HND in Computing/ Third Semester)


19
Data Structure & Algorithm 2020

Class NODE<T>

Class NODE<T> is considered as a node (T is a generic type in Java to store every types of data). It
is used to store a collection of Product; it can be identified as MyT<Product>. It has two values:

+ info : Product – data of one Product.

+ next : MyT<Product> - reference to the next Product in the list, or maybe null.

With 4 methods:

+ getInfo() : return data of Product

+ setInfo() : set data to Product

+ getNext() : return the next MyT<Product>

+ setNext() : set the next MyT<Product>

Class MyListT<T>

Class MyLinkedListT<T> is a list of nodes. This class is implemented as a Linked List Class from
scratch in Java. In this program, a collection of Product is stored in this class, it can be identified as
MyLinkedListT<Product>. It has two values:

+ head : MyT<Product> - the first product in the list.

+ tail : MyT<Product> - the last product in the list.

With these operations:

+ isEmpty() : is a Boolean type, return true if the list do not have a head.

+ getHead() : return the first product in the list.

+ getTail() : return the last product in the list.

(BTEC HND in Computing/ Third Semester)


20
Data Structure & Algorithm 2020

+ removeHead() : delete the first product in the list. Set the next Product of the first item in the list is
the new head then remove the old one.

The function works only when the list is not empty.

If the list has only one node which is both head and tail, that node will be set null

| if (length of list == 1) head = tail = null;

Else if the list has more than one node:

+ Declare a temporary node and set as the next node of the current head

| MyT<Product> temp = head.getNext();

+ Delete the current head

| head.setNext(null);

+ Set the new head as a temporary node declared at the first place

| head = temp;

+ removeTail() : delete the last product in the list. Loop to the previous of the last item of the list, set
it as a new tail then remove the old one.

- The function works only when the list is not empty.

- If the list has only one node which is both head and tail, that node will be set null

| if (length of list == 1) head = tail = null;

- Else if the list has more than one node:

+ Declare a temporary node and set as the current head.

| MyT<Product> temp = head;

+ Access respectively from the head to the next element (loop the get next function)
until reach the previous node of the tail.

| while(temp.getNext() != tail)

| {temp = temp.getNext();}

(BTEC HND in Computing/ Third Semester)


21
Data Structure & Algorithm 2020

+ Delete the current tail then set the new tail as a temporary node declared as a
previous node of the old tail.

| temp.setNext(null);

| tail = temp;

+ traverse() : print to screen all the Products from the list

- The function works only when the list is not empty.

- Declare a temporary node and set as the current head.

| MyT< Product > temp = head;

- Access respectively from the head to the tail of the list (loop the get next function) and print
every Product’s information that it found.

| while (temp != null)

| | print temp.getInfo();

| | temp = temp.getNext();

Output:

+ getLength() : count all Products in the list, return an integer number.

- Declare integer i = 0.

| int i = 0;

(BTEC HND in Computing/ Third Semester)


22
Data Structure & Algorithm 2020

- If the list is not empty, loop from the first to the last Product of the list to count all elements
in the list by adding one to i each time it accesses through one product, then return i number.

- Else if the list is empty, return i = 0.

+ add(Product info) : add a Product to list.

- Declare a new Product node with its information but no references linked node.

| MyT< Product > n = new MyT<>(info,null);

- If the list is not empty, newest node will be set as the next node of the current tail. Finally,
set the newest node as the new tail of the list, which means the old tail becomes the previous node of
the new tail.

| tail.setNext(n);

| tail = n;

- If the list is empty, the newest added Product is both head and tail.

| if (isEmpty()) {head = tail = n;}

(BTEC HND in Computing/ Third Semester)


23
Data Structure & Algorithm 2020

+ get(int index) : returns the product at the specified position in this list.

- Declare a new Product node and set as null

| MyT< Product > current = null;

- If the list is empty, return null.

- If the list is not empty, access respectively from the head to the next element (loop the get
next function) until reach the index position node by declaring integer i = 0, then loop from i to the
number of specified position to get the product which user put in.

| for (i = 0  index) {

| | current = current.getNext();

- If the loop finds the index position, return the information of the Product.

| | return current.getInfo();

- If the loop cannot find the index position, return null.

+ remove(int index) : is a Boolean type, delete the Product at the specified position in this list.

- Declare a new Product node and set as head

| MyT<Product> current = head;

- If the list is empty, return false to stop the process

- If index number that user put in is zero, which means the position of the node is the head of
the list, the fuction removeHead() will be called to delete the head of the list.

| if (!isEmpty()) {

| if(index == 0){

| | removeHead();

| | print ("Deleted");

(BTEC HND in Computing/ Third Semester)


24
Data Structure & Algorithm 2020

| | return true;

- Else if the index number is greater than 0, access respectively from the next node of the
head to the next element (loop the get next function) until reach the tail node by declaring integer i =
1, then loop from i to the number of last position of the list. From here, the function will search for
previous node of the index position node.

| | for (i = 1  getLength())

| | | | if(i==index)

- If it finds the previous node of the index position node, it will set the next node of the
previous node as the next node of the index position node, then sort sequentially to all the nodes after
the deleted node. The index position node is fully deleted. After all, return true.

| | | | current.setNext(current.getNext().getNext());

| | | current = current.getNext();

| | return true;

(BTEC HND in Computing/ Third Semester)


25
Data Structure & Algorithm 2020

+ removeAfter (int index): is a Boolean type, delete the next Product of the Product that user
chooses. It operates similar to remove() method but only change the declaration of integer i (i=0)
when looping the list to get the position (but remove the removeHead() function from it)

- Declare a new Product node and set as head

| MyT<Product> current = head;

- If the list is empty, return false to stop the process

- Start accessing respectively from the the head to the next element (loop the get next
function) until reach the tail node by declaring integer i = 0, then loop from i to the number of last
position of the list. From here, the function will search for the index position node.

| | for (i = 0  getLength())

| | | | if(i==index)

- If it finds the index position node, it will set the next node of the index position node as the
next node of the node after the index position node, then sort sequentially to all the nodes after the
deleted node. The node after the index position node is fully deleted. After all, return true.

| | | | current.setNext(current.getNext().getNext());

| | | current = current.getNext();

| | return true;

Judgements

(BTEC HND in Computing/ Third Semester)


26
Data Structure & Algorithm 2020

This program has built the implementation of Linked List from the scratch because of its advantages,
but also some disadvantage matters are still visible:

The size of the linked list is so flexible and almost “infinite” (depending on the computer's memory).
Adding or removing from one side of the list is simple because Linked List can grow and shrink
during run time. But if adding or removing the node at the middle of the list is more complex than
arrays.

When user want to access to elements in the linked list, the application need to browse sequentially
all element. It slows down the process and takes more time than arrays (Accessing to the elements in
the array is accessed directly based on index).

The most important advantage of using Linked List in this program is that Linear Data Structures
such as Stack, Queue can be easily implemented using Linked list.

Coding

Figure -Implement the node of a single linked list

(BTEC HND in Computing/ Third Semester)


27
Data Structure & Algorithm 2020

Initialization Product class

Figure -Initialization Product class

(BTEC HND in Computing/ Third Semester)


28
Data Structure & Algorithm 2020

Initialization MyProductList class

Figure -Initialization MyProductList class

(BTEC HND in Computing/ Third Semester)


29
Data Structure & Algorithm 2020

Operations on this data structures


Load data from file

Figure Load data

Demo load data

(BTEC HND in Computing/ Third Semester)


30
Data Structure & Algorithm 2020

Figure -Demo load data

(BTEC HND in Computing/ Third Semester)


31
Data Structure & Algorithm 2020

Add new item

Figure Add new item

Demo add product

Figure -Demo add product

(BTEC HND in Computing/ Third Semester)


32
Data Structure & Algorithm 2020

Display all product list

Figure -Display product list

Figure -corresponding algorithm to display

Demo display product

(BTEC HND in Computing/ Third Semester)


33
Data Structure & Algorithm 2020

Figure -Demo display product

(BTEC HND in Computing/ Third Semester)


34
Data Structure & Algorithm 2020

Save data

Figure -Save data

Figure -corresponding algorithm to save data

Demo save data

(BTEC HND in Computing/ Third Semester)


35
Data Structure & Algorithm 2020

Figure -demo save data

Search product

Figure -Search product

Figure -corresponding algorithm to search product

(BTEC HND in Computing/ Third Semester)


36
Data Structure & Algorithm 2020

Demo search product

Figure- Demo search product

Delete product by Pcode

Figure 1 Delete product by Pcode

(BTEC HND in Computing/ Third Semester)


37
Data Structure & Algorithm 2020

Figure - corresponding algorithm to delete product

Demo delete product

(BTEC HND in Computing/ Third Semester)


38
Data Structure & Algorithm 2020

Figure- Demo delete product

(BTEC HND in Computing/ Third Semester)


39
Data Structure & Algorithm 2020

Delete the node after the node having code = xCode

Figure-Delete product behind product has pcode

Figure - corresponding algorithm to delete product behind product has pcode

Demo Delete the node after the node having code = xCode

(BTEC HND in Computing/ Third Semester)


40
Data Structure & Algorithm 2020

Figure -Demo Delete product behind product has pcode

(BTEC HND in Computing/ Third Semester)


41
Data Structure & Algorithm 2020

Sort Pcode by Insertion sort

Figure -Insertion sort in array

Figure -corresponding algorithm to insertion sort in array

(BTEC HND in Computing/ Third Semester)


42
Data Structure & Algorithm 2020

Demo insertion sort for pcode

Figure 2 Demo insertion sort for pcode

Sort Pcode by Quick sort

Figure -Quick sort in array

(BTEC HND in Computing/ Third Semester)


43
Data Structure & Algorithm 2020

Figure -corresponding algorithm to quick sort in array

Demo quick-sort for Pcode

(BTEC HND in Computing/ Third Semester)


44
Data Structure & Algorithm 2020

Figure - Demo quick-sort for Pcode

(BTEC HND in Computing/ Third Semester)


45
Data Structure & Algorithm 2020

Stack
Stack is a special kind of list that adding or removing an element at one side of the list called the top
(vertex). It has these basic operations: adding (push) and removing elements (pop), which will carry
out the latest object. Stack is also known as LIFO data structure (Last In First Out).

In “Data Structures and Algorithms in Java, Second Edition by Adam Drozdek”, it is defined (the
definition has been edited by this report’s writer):

“A stack is a linear data structure that can be accessed only at one of its ends for storing and
retrieving data. New node is put on the top of the stack and taken off the top. The last node put on the
stack is the first tray removed from the stack. For this reason, a stack is called an LIFO structure:
last in/first out”.

Examples of LIFO type: A stack of books on the desk. When you want to add a book onto the stack
of books, the book will be put at the top of the pile of books. When you want to take out one book of
the stack, book on top of the stack will be taken out, which means the latest book is removed first.

Stacks can be built based on the implementation of arrays or linked lists. To install the stack using
linked list, we use singly linked list. Because of the function of the linked list, adding and removing
an element from the list will be so simple and so quick that element is only located at the top of the
list. Therefore, we will store the stack in order: the last element of the list (tail) is the top of the
stack... For adding element onto the stack, we created 1 new node and add it to the top of the stack.
To take one element out from the stack, we also just take the top node.

(BTEC HND in Computing/ Third Semester)


46
Data Structure & Algorithm 2020

Implementation of Stack
- Stack used in this program is implemented based on Linked List class (MyListT<T>). A collection
of Customer will be stored in this class, it can be identified as MyCustomerStackT<Customer>.
Here is the initialized class:

Class MyCustomerStackT<T>

+ MyListT<T> list //implement linked list class

The following operations are needed to properly manage a stack:

+ push(Customer c) : push (stores) a new element onto the stack as the top, which means the latest
added Customer is the new tail of the linked list.

| return list.add(item); //add an item to the top

+ pop() : remove and get the top data element of the stack, which means access and delete the tail of
the linked list. Return the data of the popped-out Customer.

| T item = list.getTail().getInfo(); //get information of the top

| list.removeTail(); //delete the top

| return item;

(BTEC HND in Computing/ Third Semester)


47
Data Structure & Algorithm 2020

+ top () : gets the top data element of the stack, without removing it. Return the data of the top of the
stack, also known as the tail of the linked list.

| return list.getTail().getInfo(); // get information of the top

+ isEmpty() : is a Boolean type, return true if the stack is empty. Implement from Linked List class.

+ getLength() : counts all Customers on the stack, return an integer number. Implement from Linked
List class.

(BTEC HND in Computing/ Third Semester)


48
Data Structure & Algorithm 2020

+ get(int index): returns the customer at the specified position on this stack. Implement from Linked
List class.

+ traverse() : prints to screen all the Products on the stack. Implement from Linked List class.

+ remove(int index) : is a Boolean type, deletes the Customer at the specified position on the stack.
Implement from Linked List class.

Judgements

Advantages and disadvantages of using Stack in this program is pretty like Linked List. The only
difference is the LIFO structure, which makes pop() function takes out the latest Customer from the
stack quicker.

Thus, we can see that if a stack was installed by the linked list, its size is almost "infinite" (depending
on the computer's memory). We can add new or remove anytime we want because the push () and
pop() operations is quite simple. However, there is still many complex actions than stack array, such
as accessing to one element in the middle of the stack, changing the position of an element, etc.…

When user want to access to elements in the linked list, the application need to browse sequentially
from the top to get all elements. It may slowly run and takes more time than stack arrays (Accessing
to the elements in the array is accessed directly based on index).

Coding Part

(BTEC HND in Computing/ Third Semester)


49
Data Structure & Algorithm 2020

Figure-Customer list using stack data structure

(BTEC HND in Computing/ Third Semester)


50
Data Structure & Algorithm 2020

Initialization Customer class

Figure - Initialization Customer class

(BTEC HND in Computing/ Third Semester)


51
Data Structure & Algorithm 2020

Operations on this data structures


Load data from file

Figure 3 Load data

Demo load data

(BTEC HND in Computing/ Third Semester)


52
Data Structure & Algorithm 2020

Figure 4 Demo load data customer

(BTEC HND in Computing/ Third Semester)


53
Data Structure & Algorithm 2020

Add new item

Figure 5 Add new customer

Demo add new customer

(BTEC HND in Computing/ Third Semester)


54
Data Structure & Algorithm 2020

Figure-Demo add new customer

Display all customer data

Figure - Display customer data

(BTEC HND in Computing/ Third Semester)


55
Data Structure & Algorithm 2020

Demo display customer list

Figure -Demo display customer list

(BTEC HND in Computing/ Third Semester)


56
Data Structure & Algorithm 2020

Save data to file

Figure -Save data

Demo save data

Figure- Demo save data

(BTEC HND in Computing/ Third Semester)


57
Data Structure & Algorithm 2020

Search customer by pcode

Figure -Search customer

Demo search customer

Figure - Demo search customer

(BTEC HND in Computing/ Third Semester)


58
Data Structure & Algorithm 2020

Delete customer by Ccode

Figure- Delete customer by ccode

Demo delete customer

(BTEC HND in Computing/ Third Semester)


59
Data Structure & Algorithm 2020

Figure -Demo delete customer

(BTEC HND in Computing/ Third Semester)


60
Data Structure & Algorithm 2020

P2 Determine the operations of a memory stack and how it is used to implement function calls
in a computer.

Stack memory
According to (Study.com 2019)

The stack memory segment is an area of memory allotted for automatic variables. Automatic
variables are allocated and de-allocated automatically when program flow enters and leaves the
variable's scope. Stack memory is allocated and de-allocated at the top of the stack, using Last-In-
First-Out (LIFO). (Anon, 2019) Because of this process, stack allocation is simpler and typically
faster than heap allocation. In most modern computer systems, each thread has its own stack memory
segment, the size of which can be small as little as a few dozen kilobytes. Allocating more memory
on the stack than is available can result in a stack overflow error, which is frequently associated with
security issues. (Anon, 2019)

Basic operations in stack data structure

Memory stack is a linear data structure (location) used to store data in the computer's memory. They
can also be called queues. Data in a stack must always be the same type. An example of a stack is
illustrated in Figure 8 below,

Figure 8. Examples of Stacks/ Queues.

Items in the stack are inserted or deleted in a linear order and do not follow any random string. As in
any queue or collection that is assembled, data items in the stack are stored and accessed in a specific

(BTEC HND in Computing/ Third Semester)


61
Data Structure & Algorithm 2020

way. In this case, a technique called LIFO (Last In First Out) is used. This involves a series of insert
and removal operations that we will discuss in the following section.

LIFO (Last In First Out)


When a stack is accessed (there are inserted or deleted items), it is done in an orderly manner by
LIFO. LIFO stands for Last In First Out. Computers use this method to request service data that the
computer's memory receives. LIFO dictates that data is last inserted or stored in any particular stack,
must be the first data to be deleted. If that applies to our queue for movies in Figure 1 above, there
will be chaos! The operations on the stack are discussed in the following sections with Figure 9
below:

Figure 9. LIFO (Last In First Out)

The Push Operation


Push operation involves inserting data items into a stack. Let us check our restaurant plate dispenser
in Figure 9. Operation pushes additional plates (data items) into the plate dispenser (stack). The first
plate is pushed down to the bottom of the stack with all subsequent plates in the following order after
it. The first inserted data item is the most inaccessible and is located at the bottom of the stack.

The Pop Operation


Pop operation involves removing data items from the loaded stack. In our plate distributor
illustration, the last sheet (data item) added is placed at the top of the stack. This data item
is turned off the stack as the first item is deleted. Think of the spring loading system in the
base of the plate distributor. It pushes the stack on top each time you remove the plate. In
memory, items continue to be turned on in that order.

(BTEC HND in Computing/ Third Semester)


62
Data Structure & Algorithm 2020

The Peek Operation


In this operation, no data items are added or deleted from the stack. The snapshot operation only
requires the address location of the data item at the top of the stack (the last item is pushed).

The Search Operation


In this operation, it do not have any data items are added or deleted from the stack. The search
operation require that geographical local of any data items in the stack. It located the item at the top
of the stack.

How it is used to implement function calls in a computer

Stack memory in computers


The stack memory (RAM) is a special kind of memory that is used to store information temporarily,
when we want to read the information correctly in the opposite direction to the recorded memory,
without caring about the organization data addressing.

Stack memory is sequential memory with specify access restrictions that allow writing and reading
information to or from only one location in this memory called the top of the stack. The stack
memory acts as a queue where data can be written to the top of the stack, while changing all the
information stored in subsequent locations in a location according to the depth of the queue. this. Can
only read from the stack from the top of the stack. Reading makes information from the top of the
stack removed and a new information is recorded in its place from the depth of the stack with the
displacement of all information stored in one position to the top. of stack. Then the queue is the last
type to enter first.

The stack memory works in the same way as the rifle magazine, in which the introduction of a new
bullet box pushes all the remaining cartridges into the depths of the magazine and the use of
cartridges (one shot) makes The top cartridge is removed and replaced with the first cartridge under
the used one.

Three instructions are used to manipulate the stack are push (write data into the stack), read stack
( read the top of the stack), pop (delete data from the top of the stack with a shift of its contents up).

(BTEC HND in Computing/ Third Semester)


63
Data Structure & Algorithm 2020

Sometimes, symmetric operations involve the top two positions of the stack used as arguments and
positions for the results. After pure operation, pop operation is performed and results are available at
the top of the stack.

Figure 10. Stack functioning principles

The first stack deployment is based on the use of registers, in which data is moved in a parallel
manner during Push and Pop operations.

Modern stack deployment is based on the main memory usage supported by special registers that
make it easy to access and manage the stack. A stack is reserved by the operating system, sequences
of consecutive memory locations. The boundary of the stack is determined by two special registers -
the stack base register and the stack limit register hold the address of the stack top and lower
boundary positions. The address space between these addresses is excluded from other uses than the
stack implementation. The top of the stack is determined by keeping the address in the third register
called the stack pointer register.

Before the computer starts executing the program, the top of the stack register is set to the contents
of the stack base register. After each Push operation, the contents of the stack pointer register are
changed according to the number of bytes corresponding to the stack in the stack limit direction.
After each Pop operation, the content of the stack pointer is changed in the direction of the stack
base.

(BTEC HND in Computing/ Third Semester)


64
Data Structure & Algorithm 2020

Figure 11. Stack implementation the computer- the top of the stack
in the memory.

The figure above shows the organization of the stack in the main memory, in which the top of the
stack is accessed only in memory. Another solution, shown in the figure below, assumes that the top
of the stack and the position just below the top, is stored in special processor registers: the top of the
stack register and the top register -first.

(BTEC HND in Computing/ Third Semester)


65
Data Structure & Algorithm 2020

Figure-. Stack implementation in the computer- the top of the stack in registers.

Stack memory implements function call in computer


Among the instructions that control computers, we can find subroutine call instructions with the
acronym "Call" and instructions for returning subroutines with the acronym "Ret".

A subroutine is a series of instructions that end with the "Ret" return command. In the subroutine the
subroutine always has the address of the first instruction in a subprogram called the subroutine
address.

Mechanism of subroutine calls and the execution of the "Call" i "Ret" commands based on the use
of the stack.

Execute the "Call" subroutine command including:

3. stored in the stack of the program counter's current content (ie, the return address executes
the next instruction after the call) with the "Push" operation,

(BTEC HND in Computing/ Third Semester)


66
Data Structure & Algorithm 2020

4. write to the program that accesses the embedded address in the "Call" guide,
5. take the next tutorial according to the new content of the program counter.

The address written to the stack will be used by the "Ret" return command to automatically return
from the subroutine to the next command.

Instructions "Call".

The return execution from the "Ret" subcommand includes:

1. Read from the top of the stack of the return address (to successfully instruct the "call"
command),
2. write this address to the program counter,
3. perform the "Pop" operation on the stack,
4. Fetch a new guide according to the new content of the program counter.

The address written to the stack in a subroutine call is sometimes called a trace and the
subroutine call is called a hop with a trace.

Often use nested subroutine calls, in which during subroutine execution, new subroutine is called
from its body. The mechanism of returning from trace subroutines stored in the stack allows to
automatically return the next program call context with the correct return order preserved.

The figure below shows actions related to nested subroutine calls from a top program thread. In the
subroutine call 1 (Call 500 is stored at address 100), the return address 101 is stored in the stack. In
the call of subprogram 2 (Call 900 is written at address 600), the return address 601 is saved in the
stack. When returning from sub-program 2, address 601 is taken from the stack. When returning
from subroutine 1, address 101 is taken from the stack.

(BTEC HND in Computing/ Third Semester)


67
Data Structure & Algorithm 2020

Figure. The use of stack in subroutine calls

To Sum Up, As I have already discussed stack memory is the allocated space for the store of the data
in the computer. It is provided at the compile or run
time of the program or any function.

In our computer system there is RAM (Random


Access Memory) which stores our temporary data in
the run time of the computer and make us available
whenever it is necessary. data store in stack are also
save in a computer memory (RAM). So, stack is a
special region of memory, and automatically managed
by the CPU so you don’t have to allocate or deallocate
memory. Once the system is closed then the RAM will lose its data and when system open it start
from the beginning. Exactly, same as that we can compare stack memory to RAM such that they
store the temporary variables created by each function.

(BTEC HND in Computing/ Third Semester)


68
Data Structure & Algorithm 2020

M1 Illustrate, with an example, a concrete data structure for a FIFO queue


First in First out (FIFO) Queue:

The queue is a data structure like the stack, but differs in the way that an element to be taken out of
the collective element. Opposed to the stack, the element is removed from the queue is not the
newest element be put into the element, but the one that is already stored and waited in the queue.

In “Data Structures and Algorithms in Java, Second Edition by Adam Drozdek”, it is defined (the
definition has been edited by this report’s writer):

“A queue is simply a waiting line that grows by adding elements to its end and shrinks by
taking elements from its front. Unlike a stack, a queue is a structure in which both ends are used: one
for adding new elements and one for removing them. Therefore, the last element should wait until all
elements preceding it on the queue are removed. A queue is an FIFO structure: first in/first out.”

The queue is a FIFO structure type (First in First Out). Examples of the queue have a lot in practice:
A line of people waiting at the cinema, or the supermarket, etc.… In the computer field there are also
many examples of the queue: A set of tasks waiting served by the computer operating system.

Queues can be built based on the implementation of arrays or linked lists. To install the queue using
linked list, we use singly linked list. Because of the function of the linked list, adding and removing
an element from the list will be liked the getHead() or getTail() functions. Therefore, we will store
the queue in order: To add element onto the queue, we created 1 new node and add it to the tail of the
queue. To take one element out from the queue, we remove the head of the queue.

(BTEC HND in Computing/ Third Semester)


69
Data Structure & Algorithm 2020

B. Implementation of Queue
Queue used in this program is implemented based on Linked List class (MyListT<T>). A collection
of Ordering will be stored in this class; it can be identified as MyOrderQueueT<Ordering>. Here is
the initialized class:

Class MyOrderQueueT<T>

+ MyLinkedListT<T> list //implement linked list class

The following operations are needed to properly manage a queue:

+ enqueue (Ordering o): push (store) a new element into the Queue. The new added Ordering is the
new tail.

| return list.add(item); //add an item to the tail

+ dequeue() : remove and get the head element of the queue. Return the data of the dequeued
Ordering.

| T item = list.getHead().getInfo(); //get information of the head

| list.removeHead(); //delete the head

| return item;

(BTEC HND in Computing/ Third Semester)


70
Data Structure & Algorithm 2020

+ front() : gets the head element of the queue, without removing it.

| return list.getHead().getInfo(); //get information of the head

+ isEmpty() : is a Boolean type, return true if the queue is empty. Implement from Linked List class.

+ getLength() : counts all Orderings in the queue, return an integer number. Implement from Linked
List class.

+ get(int index): returns the Ordering at the specified position in this queue. Implement from Linked
List class.

+ traverse() : prints to screen all the Orderings in the queue. Implement from Linked List class.

+ remove(int index) : is a Boolean type, deletes an Ordering at the specified position in this queue.
Implement from Linked List class.

Judgements

Advantages and disadvantages of using Queue in this program is pretty like Linked List and Stack.
The only difference is the FIFO structure, which makes dequeuer() function takes out the longest
awaited Ordering from the queue quicker.

Thus, we can see that if a queue was installed by the linked list, its size is almost "infinite"
(depending on the computer's memory). We can add new or remove anytime we want because the

(BTEC HND in Computing/ Third Semester)


71
Data Structure & Algorithm 2020

enqueue() and dequeue() operations is quite simple. However, there is still many complex actions
than queue array, such as accessing to one element in the middle of the stack, changing the position
of an element, etc.…

When customer want to access to products in the linked list, the application need to browse
sequentially from the head to the tail to get all elements. The speed of processing is not as fast as
queue array (Accessing to the elements in the array is accessed directly based on index).

 Comparing Stack and Queue and Judgements

Example-: A queue can be very helpful when the order of the product form customer and it is
essential and needs to be exactly constant when the elements enqueue into the program. SMS
application of Shop-Now online Ecommerce has chosen Queue structure to store ordering elements
because of its feature first in/first out. In this way, the orderings will be processed in turns like
waiting in a line so that there will not have any isolated cases happening.

A stack can be significant when user want to temporarily accumulate an element which is going to be
used in the immediate step(s). Stack structure is chosen to store Customer data in the application
because of its order last in/first out to have special attention to the newest customers.

(BTEC HND in Computing/ Third Semester)


72
Data Structure & Algorithm 2020

Functionality of queue with different operations (with code):


Basically, there are two different types of the functionality talking about the queue they are enqueue
and dequeue. Enqueue is used to store the data whereas the dequeue is used to delete the data. Here I
am going to display the screenshot of the codding which I have done to store the data of Shop-Now
online Ecommerce company queue.

Coding

Figure -Order list using queue data structure

(BTEC HND in Computing/ Third Semester)


73
Data Structure & Algorithm 2020

Initialization order class

Figure -Initialization order class

(BTEC HND in Computing/ Third Semester)


74
Data Structure & Algorithm 2020

Operations on this data structures


Input data

Figure -Input order

(BTEC HND in Computing/ Third Semester)


75
Data Structure & Algorithm 2020

Demo input data

Figure -Demo input order

(BTEC HND in Computing/ Third Semester)


76
Data Structure & Algorithm 2020

Display all order

Figure -Display all order

Demo display data

Figure-Demo display data

(BTEC HND in Computing/ Third Semester)


77
Data Structure & Algorithm 2020

Sort Pcode by selection sort

Figure 6 Sort by pcode

Figure 7 corresponding algorithm to sort by pcode

Demo sort Pcode

(BTEC HND in Computing/ Third Semester)


78
Data Structure & Algorithm 2020

Figure Demo sort Pcode

(BTEC HND in Computing/ Third Semester)


79
Data Structure & Algorithm 2020

Sort Ccode by merge sort

Figure 8 Sort by Ccode

Demo sort Ccode

(BTEC HND in Computing/ Third Semester)


80
Data Structure & Algorithm 2020

Figure - Demo sort Ccode

Queue in merge sort and selection sort for Shop-Now online Ecommerce Company:
For the Shop-Now online Ecommerce Company, I have used the queue data structure for merge sort
and selection sort data. With the help of the queue the specific data can be search easily. I have
illustrated the searching operation while doing the codding which can be seen in the above
screenshot. Sorting means the process of arranging the data for specific purpose like: searching,
adding, deleting, etc. for that purpose I have use the queue for storing the data of the Shop-Now
online ecommerce management system. In a sentence it can be concluded that the data with the help
of the queue the sorting and searching process can be done easily.

(BTEC HND in Computing/ Third Semester)


81
Data Structure & Algorithm 2020

M3 Compare the performance of two sorting algorithms

Sorting
Sorting is the process of rearranging the elements in a certain order. The main purpose of the
arrangement is to make the search operations on the collective element easier. Sorting significantly
reduces the complexity of problems and searching, the efficiency of data handling is substantially
increased. Sorting is extremely important in development of programs in Computer science.

Example of sorting in life: the word in the dictionary is organized alphabetically; products in a store
are organized by code, by name, etc...

Overall, there is a lot of data processing operations in coding needed to sort the data elements in the
order given. There are many different sorting algorithms, from simple to complex.

The sorting algorithm is also a good example of the variety of algorithms. With same purpose, but
there are many ways of implementation, each way has its own advantage and better than the other.

Normally, sorting algorithms are divided into two types. The first type is the algorithm is simple to
install, but not efficient, it called “Elementary Sorting Algorithms”. The second type, which is the
complicated algorithm but more efficient in terms of speed, is called “Efficient Sorting Algorithms”.
If the data has few elements, it should be used the first type. Else if the data has many elements, the
second type is the best choice.

(BTEC HND in Computing/ Third Semester)


82
Data Structure & Algorithm 2020

Two types of sorting algorithms:

1. Elementary Sorting Algorithms:

Selection Sort

Insertion Sort

Bubble Sort

2. Efficient Sorting Algorithms

Shell sort

Quick Sort

Merge Sort

Heap sort

Radix sort

In Show-Now online ecommerce company is applied these sorting algorithms:

Insertion Sort (elementary sorting algorithms)


Definitions

Insertion sort is a sorting algorithm based on comparing in-place. We can simply understand this
algorithm like: Checking values of the first and the second element in a list, comparing between
them if they are in an order, if not, they will be swap the position. And the algorithms will repeatedly
and respectively execute between the second and the third element and so on until it reaches the end
of the list.

- In “Data Structures and Algorithms in Java, Second Edition by Adam Drozdek”, it is defined (the
definition has been edited by this report’s writer):

“An insertion sort starts by considering the two first elements of the array data, which are
data[0] and data[1]. If they are out of order, an interchange takes place. Then, the third element,
data[2], is considered and inserted into its proper place. If data[2] is less than data[0] and data[1],

(BTEC HND in Computing/ Third Semester)


83
Data Structure & Algorithm 2020

these two elements are shifted by one position; data[0] is placed at position 1, data[1] at position 2,
and data[2] at position 0. If data[2] is less than data[1] and not less than data[0], then only data[1]
is moved to position 2 and its place is taken by data[2]. If, finally, data[2] is not less than both its
predecessors, it stays in its current position. Each element data[i] is inserted into its proper location
j such that 0 # j # i, and all elements greater than data[i]are moved by one position”.

Here is an example of step by step using Insertion Sort:

Selection sort:

Selection sort has achieved slightly better performance and is efficient than bubble sort algorithm.
Suppose we want to arrange an array in ascending order then it functions by finding the largest

(BTEC HND in Computing/ Third Semester)


84
Data Structure & Algorithm 2020

element and exchanging it with the last element, and repeat the following process on the sub-arrays
till the whole list is sorted

In selection sort, the sorted and unsorted array doesn’t make any difference and consumes an order of
n2 (O(n2)) in both best- and worst-case complexity. Selection sort is faster than Bubble sort.

Comparison between Insertion sort and Selection sort

Comparison Insertion sort Selection sort


Definition Insertion sort works by inserting Selection sort perform sorting by

(BTEC HND in Computing/ Third Semester)


85
Data Structure & Algorithm 2020

the set of values in the existing


searching for the minimum value
sorted file. It constructs the sorted
number and placing it into the first or
array by inserting a single element
last position according to the order
at a time. This process continues
(ascending or descending). The
until whole array is sorted in some
process of searching the minimum
order. The insertion sort method
key and placing it in the proper
saves an effective amount of position is continued until the all the
memory. elements are placed at right position.
Basic The data is sorted by inserting the
The data is sorted by selecting and
data into an existing sorted file.
placing the consecutive elements in
sorted location.
Nature Stable Unstable
Process to be Elements are known beforehand Location is previously known while
followed while location to place them is elements are searched.
searched.
Immediate data Insertion sort is live sorting It cannot deal with immediate data, it
technique which can deal with needs to be present at the beginning.
immediate data.
Complexity O(n) O(n2)
Advantages - Easily implemented and very - Easily implemented
efficient when used with small sets
of data.
- The additional memory space
requirement of insertion sort is less
(i.e., O(1)).
- It is considered to be live sorting
technique as the list can be sorted
as the new elements are received.
- It is faster than selection sorting
algorithms.
Figure -Comparison insertion sort and selection sort

Among both of the sorting algorithm, the insertion sort is fast, efficient, stable while selection sort
only works efficiently when the small set of elements is involved or the list is partially previously
sorted. The number of comparisons made by selection sort is greater than the movements performed
whereas in insertion sort the number of times an element is moved or swapped is greater than the
comparisons made.

Demo and implement

(BTEC HND in Computing/ Third Semester)


86
Data Structure & Algorithm 2020

Insertion sort
Implement insertion sort

Figure 9 Insertion sort

Figure- corresponding algorithm

(BTEC HND in Computing/ Third Semester)


87
Data Structure & Algorithm 2020

Demo insertion sort

Figure - Insertion sort step 1 & 2 & 3

(BTEC HND in Computing/ Third Semester)


88
Data Structure & Algorithm 2020

Figure -Insert sort step 4

Figure - Insert sort result

(BTEC HND in Computing/ Third Semester)


89
Data Structure & Algorithm 2020

Selection sort
Implement selection sort

Figure -Sort by selection sort

Figure -corresponding algorithm to sort

(BTEC HND in Computing/ Third Semester)


90
Data Structure & Algorithm 2020

Demo selection sort

Figure - Selection sort step 1 & 2

(BTEC HND in Computing/ Third Semester)


91
Data Structure & Algorithm 2020

Figure -Selection sort step 2 & 3

(BTEC HND in Computing/ Third Semester)


92
Data Structure & Algorithm 2020

Figure - Selection sort result

(BTEC HND in Computing/ Third Semester)


93
Data Structure & Algorithm 2020

D1 Analyse the operation, using illustrations, of two network shortest path algorithms,
providing an example of each

Dijkstra’s algorithm:
Edsger Dijkstra discovered Dijkstra’s algorithm in 1959. his algorithm solves the single-source
shortest-path problem by finding the shortest path between a given source vertex and all other
vertices. This algorithm works by first finding the path with the lowest total weight between two
vertices. j and k. It then uses the fact that a node r, in the path from j to k implies a minimal path
from j to r. In the end, we will have the shortest path from a given vertex to all other vertices in the
graph. Dijkstra’s algorithm belongs to a class of algorithms known as greedy algorithms. A greedy
algorithm makes the decision that seems the most promising at a given time and then never
reconsiders that decision.

The time complexity of Dijkstra’s algorithm is dependent upon the internal data structures used for
implementing the queue and representing the graph. When using an adjacency list to represent the
graph and an unordered array to implement the queue the time complexity is O(n2), where n is the
number of vertices in the graph. However, using an adjacency list to represent the graph and a min-
heap to represent the queue the time complexity can go as low as O(e*log n), where e is the number
of edges. It is possible to get an even lower time complexity by using more complicated and
memory intensive internal data structures.

Working of Dijkstra’s algorithm

(CodinGame 2019)

- Mark your selected initial node with a current distance of 0 and the rest with infinity.

- Set the non-visited node with the smallest current distance as the current node C.

- For each neighbor N of your current node C: add the current distance of C with the weight of the
edge connecting C-N. If it's smaller than the current distance of N, set it as the new current
distance of N.

- Mark the current node C as visited.

- If there are non-visited nodes, go to step 2.

For example

(BTEC HND in Computing/ Third Semester)


94
Data Structure & Algorithm 2020

- Let's study the algorithm with an explained example! Let's calculate the shortest path between
node C and the other nodes in our graph:
-

- (CodinGame 2019)

During the algorithm execution, we'll mark


every node with its minimum distance to node
C (our selected node). For node C, this
distance is 0. For the rest of nodes, as we still
don't know that minimum distance, it starts
being infinity (∞):

We'll also have a current node. Initially, we


set it to C (our selected node). In the image,
we mark the current node with a red dot.
Now, we check the neighbors of our current
node (A, B and D) in no specific order. Let's
begin with B. We add the minimum distance
of the current node (in this case, 0) with the
weight of the edge that connects our current
node with B (in this case, 7), and we obtain 0
+ 7 = 7. We compare that value with the
minimum distance of B (infinity); the lowest
value is the one that remains as the minimum
distance of B (in this case, 7 is less than
infinity):

(BTEC HND in Computing/ Third Semester)


95
Data Structure & Algorithm 2020

So far, so good. Now, let's check neighbor A.


We add 0 (the minimum distance of C, our
current node) with 1 (the weight of the edge
connecting our current node with A) to obtain
1. We compare that 1 with the minimum
distance of A (infinity), and leave the smallest
value:

OK. Repeat the same procedure for D:

Great. We have checked all the neighbors of


C. Because of that, we mark it as visited. Let's
represent visited nodes with a green check
mark:

We now need to pick a new current node.


That node must be the unvisited node with the
smallest minimum distance (so, the node with
the smallest number and no check mark).
That's A. Let's mark it with the red dot:

And now we repeat the algorithm. We check


the neighbors of our current node, ignoring
the visited nodes. This means we only check
B.
For B, we add 1 (the minimum distance of A,
our current node) with 3 (the weight of the
edge connecting A and B) to obtain 4. We
compare that 4 with the minimum distance of
B (7) and leave the smallest value: 4.

Afterwards, we mark A as visited and pick a


new current node: D, which is the non-visited
node with the smallest current distance.

(BTEC HND in Computing/ Third Semester)


96
Data Structure & Algorithm 2020

We repeat the algorithm again. This time, we


check B and E.
For B, we obtain 2 + 5 = 7. We compare that
value with B's minimum distance (4) and
leave the smallest value (4). For E, we obtain
2 + 7 = 9, compare it with the minimum
distance of E (infinity) and leave the smallest
one (9).
We mark D as visited and set our current node
to B.

Almost there. We only need to check E. 4 + 1


= 5, which is less than E's minimum distance
(9), so we leave the 5. Then, we mark B as
visited and set E as the current node.

E doesn't have any non-visited neighbors, so


we don't need to check anything. We mark it
as visited.
(CodinGame 2019)

As there are not unvisited nodes, we're done! The minimum distance of each node now
actually represents the minimum distance from that node to node C (the node we picked as our
initial node)!

Floyd-Warshall Algorithm:
Stephen Warshall and Robert Floyd independently discovered Floyd’s algorithm in 1962.

The algorithm solves a type of problem call the all-pairs shortest-path problem. Actually, the
Warshall version of the algorithm finds the transitive closure of a graph but it does not use weights
when finding a path. The Floyd algorithm is essentially the same as the Warshall algorithm except it
adds weight to the distance calculation.

This algorithm works by estimating the shortest path between two vertices and further improving that
estimate until it is optimum. Consider a graph G, with Vertices V numbered 1 to n. The algorithm
(BTEC HND in Computing/ Third Semester)
97
Data Structure & Algorithm 2020

first finds the shortest path from i to j, using only vertices 1 to k, where k<=n. Next, using the
previous result the algorithm finds the shortest path from i to j, using vertices 1 to k+1. We continue
using this method until k=n, at which time we have the shortest path between all vertices. This
algorithm has a time complexity of O(n3), where n is the number of vertices in the graph. This is
noteworthy because we must test up to n2 edge combinations.

Working of algorithm

This algorithm works by estimating the shortest path


between two vertices and further improving that
estimate until it is optimum. Consider a graph G,
with Vertices V numbered 1 to n. The algorithm
first finds the shortest path from i to j, using only
vertices 1 to k, where k<=n. Next, using the
previous result the algorithm finds the shortest path
from i to j, using vertices 1 to k+1. We continue using this method until k=n, at which time we have
the shortest path between all vertices. This algorithm has a time complexity of O(n3), where n is the
number of vertices in the graph. This is noteworthy because we must test up to n2 edge
combinations.

Input and Output

(BTEC HND in Computing/ Third Semester)


98
Data Structure & Algorithm 2020

Algorithm

Output

(BTEC HND in Computing/ Third Semester)


99
Data Structure & Algorithm 2020

Comparison between Dijkstra’s and Floyd-Warshall algorithm


Dijkstra’s algorithm Floyd-Warshall algorithm
It is a single source shortest algorithm i.e. It is all pair shortest path algorithm
SSSP.
It finds the shortest path from source to all It computes the shortest path between all
other vertices pairs of nodes
O (E log V) is the time complexity of O (V3) is the time complexity of Floyd-
Dijkstra’s algorithm Warshall algorithm
It does not work for negative edges but for It works for negative edges but not for
circle circle
It cannot be implemented on distributed It can be used in distributed system like
system graphs

Conclusion
For the completion of the project I have discuss about data structure that helps to store the data, with
different data structure like queue, linked list, stack etc. more on I have also done an insertion and
storing of the data for traffic management. I have stored the data of traffic management system in
stack with the help of link list. For the final part of the task I have deployed two different algorithms
that helps to store the data and execute the program accurately.

Part 2

Part 2: Write an article based on the following key aspects which will be published in an IT
magazine.

 Using an imperative definition, specify the abstract data type for a software stack.
 Examine the advantages of encapsulation and information hiding when using an ADT.
 Discuss the view that imperative ADTs are a basis for object orientation and, with
justification, state whether you agree.

P3 Using an imperative definition, specify the abstract data type for a software stack.

Title of this article: abstract data types and algorithms in a formal notation
Writers name:

(BTEC HND in Computing/ Third Semester)


100
Data Structure & Algorithm 2020

Introduction of article: In this article I am going to write about abstract data types and algorithms in a
formal notation. It means firstly I am going to write short paragraph about ADT and it’s type with
algorithm. Than after I will mention the justification why stack called adt with example. After that I
will mention the definition of encapsulation and data hiding. For justification I have attach the
coding screenshot. For distinction I would try to describe which is asking by question.
Body paragraph:

Introduction:
Abstract Data type (ADT) is a type (or class) for objects whose behavior is defined by a set of value
and a set of operations.

The definition of ADT only mentions what operations are to be performed but not how these
operations will be implemented. It does not specify how data will be organized in memory and what
algorithms will be used for implementing the operations. It is called “abstract” because it gives an
implementation independent view. The process of providing only the essentials and hiding the details
is known as abstraction.

In this part I am going to explain the definition of ADT as well as I am going to explain why stack is
called ADT and I am going to give the demonstration of ADT on stack. Also, I am going to explain
what is encapsulation and data hiding in OOP and after that I am going to explain how ADT help to
maintain encapsulation and data hiding. Finally, I am going to explain with examples(code) how
ADT helps to promote data hiding and encapsulation.

Abstract data type (ADT):


In computer science, an abstract data type (ADT) is a mathematical model for data types, where a
data type is defined by its behavior (semantics) from the point of view of a user of the data,
specifically in terms of possible values, possible operations on data of this type, and the behavior of
these operations. This contrasts with data structures, which are concrete representations of data, and
are the point of view of an implementer, not a user.

Formally, an ADT may be defined as a "class of objects whose logical behavior is defined by a set of
values and a set of operations". This is analogous to an algebraic structure in mathematics. What is
meant by "behavior" varies by author, with the two main types of formal specifications for behavior
being axiomatic (algebraic) specification and an abstract model. These correspond to axiomatic
semantics and operational semantics of an abstract machine, respectively. Some authors also include

(BTEC HND in Computing/ Third Semester)


101
Data Structure & Algorithm 2020

the computational complexity ("cost"), both in terms of time (for computing operations) and space
(for representing values). In practice many common data types are not ADTs, as the abstraction is not
perfect, and users must be aware of issues like arithmetic overflow that are due to the representation.
For example, integers are often stored as fixed width values (32-bit or 64-bit binary numbers), and
thus experience integer overflow if the maximum value is exceeded.

Example:

 Integers are an ADT, defined as the values ..., −2, −1, 0, 1, 2, ..., and by the operations of
addition, subtraction, multiplication, and division, together with greater than, less than, etc.,
which behave according to familiar mathematics (with care for integer division),
independently of how the integers are represented by the computer. Explicitly, "behavior"
includes obeying various axioms (associativity and commutativity of addition etc.), and
preconditions on operations (cannot divide by zero). Typically, integers are represented in a
data structure as binary numbers, most often as two's complement, but might be binary-coded
decimal or in ones' complement, but the user is abstracted from the concrete choice of
representation, and can simply use the data as data types.
An ADT consists not only of operations, but also of values of the underlying data and of
constraints on the operations. An "interface" typically refers only to the operations, and
perhaps some of the constraints on the operations, notably pre-conditions and post-
conditions, but not other constraints, such as relations between the operations.

 An abstract stack, which is a last-in-first-out structure, could be defined by three operations:


push, that inserts a data item onto the stack; pop, that removes a data item from it; and peek
or top, that accesses a data item on top of the stack without removal. An abstract queue,
which is a first-in-first-out structure, would also have three operations: enqueue, that inserts a
data item into the queue; dequeue, that removes the first data item from it; and front, that
accesses and serves the first data item in the queue. There would be no way of differentiating
these two data types, unless a mathematical constraint is introduced that for a stack specifies
that each pop always returns the most recently pushed item that has not been popped yet.
When analyzing the efficiency of algorithms that use stacks, one may also specify that all
operations take the same time no matter how many data items have been pushed into the
stack, and that the stack uses a constant amount of storage for each element.
Why stack is called ADT?

(BTEC HND in Computing/ Third Semester)


102
Data Structure & Algorithm 2020

ADT is a data type, just like integers and Booleans primitive data types. An ADT consist not only of
operations, but also of values of the underlying data and of constraints on the operations.

A constrains for a stack would be that each pop always returns the most recently pushed item that has
not been popped yet.

The actual implementation for an ADT is abstracted away, and we don’t have to care about. So, how
a stack is actually implemented is not that important. A stack could be and often is implemented
behind the scenes using a dynamic array, but it could be implemented with a linked list instead. It
really doesn’t matter.

The bottom line is, When we say the stack data structure, we refer to how stacks are implemented
and arrangement in the memory. But, when we say the stack ADT, we refer to the stack data type
which has set of defined operations, the operations constrain, and the possible values.

Also, from another point of view we can say that Stack operates in LIFO order. It has its own
attributes. It has its own functions for operations. The representations of those attributes are hidden
from, and of no concern to the application code. For e.g.: PUSH (S, x) is enough to push an element
x to the top of stack S, without the actual function being defined inside the main function. This is the
main concept of ADTs. Hence stack is an abstract data type.

ADT for software stack:


A software stack is a set of programs that work together to produce a result, typically an
operating system and its applications. For example, a smartphone software stack comprises the
operating system along with the phone app, Web browser and other basic applications. A
software stack may also refer to any group of applications that work in sequence toward a
common result or any set of utilities or routines that work as a group. See stack, application stack
and protocol stack. In addition, to allow them to work together, the required abstract data types
such as Stack (LIFO) and Queue (FIFO).

So in order to better understand the software stack, we find out about stack operation on Android
device. For each application running on an Android device, the runtime system will maintain an
active Stack. When an application is executed, the application's first operation is started to be
placed on the stack. When a second operation is started, it is placed on the top of the stack and
the previous activity is pushed down. Operation at the top of the recommended stack is active (or

(BTEC HND in Computing/ Third Semester)


103
Data Structure & Algorithm 2020

running). When the operation is exited, it is turned off the stack by the running time and the
operation is located just below it in the stack to become the current activity. Operations at the top
of the stack can, for example, just exit because the stack it is responsible for has been completed.
In addition, the user may have selected the Back on screen button to return to the previous
activity, causing the current activity to be disconnected from the stack by the runtime system and
therefore destroyed. A visual representation of the Android Activity Stack is illustrated in Figure
below:

As show in the diagram, new activities are pushed on to the top of the stack when they are
started. The current actiive activity is located at the top of the stack until it is either pushed down
the stack by a new activity, or popped off the stack when it exits or the user navigates to the
previous activity. In the event that resources become constrained, the runtime will kill activities,
starting with those at the bottom of the stack. The Activity Stack is what is referred to in
programming terminology as a Last- In- First- Out (LIFO) stack in the last item to be pushed
onto the stack is the first to be popped off.

(BTEC HND in Computing/ Third Semester)


104
Data Structure & Algorithm 2020

How stack operation in a website.


Applications have four tiers, three of which are on the server-side. This graphic explain the inner
working of a stack. The client is where it all startss and ends. As you know a website operation
consits of a stack of clients, HTTPs servers, APP servers and Database servers. When a the
browser send a request to the website, those request will be processed into the Queue in RAM
and will be processed for the server that handles request both in Stack (LIFO) and Queue (FIFO)
based on the type of the request. When the request is successfully processed, it will be sent back
to the client to display in browsers.

M2 Examine the advantages of encapsulation and information hiding when using an ADT.

Definition of Encapsulation:
Encapsulation is binding the code and data together in a capsule to hide the complexity of a class.
Encapsulation has less to do with access specifiers (private, public and protected). In encapsulation
members inside a class can be private, public or protected. The private members of a class are only
accessible to the objects of that class only, and the public members are accessible to the objects of
the class as well as they are accessible from outside the class. Encapsulation helps the end user of a
system to learn what to do with the system instead of how it must do.

(BTEC HND in Computing/ Third Semester)


105
Data Structure & Algorithm 2020

Let us understand encapsulation with the help of an example of a car. If a driver of a car wants to
change the gear of car, what he needs is to just change the position of the liver operating gears of the
car and it thus changes the gear of a car. A driver does not need to understand the complexity of,
what is the mechanism behind changing the gear. This is how encapsulation reduces the complexity
of a system. Encapsulation makes the system easier to operate by the end user. (System, 2019)

Abstraction provides a promise that any implementation of the ADT has certain properties and
abilities; knowing these is all that is required to make use of an ADT object. The user does not need
any technical knowledge of how the implementation works to use the ADT. In this way, the
implementation may be complex but will be encapsulated in a simple interface when it is actually
used.

The user does not need any technical knowledge of how the implementation works to use the ADT.
In this way, the implementation may be complex but will be encapsulated in a simple interface when
it is actually used.

Benefit

- The advantage of using encapsulation is that we don't need to remember the structure of the data
type to access an element, we just need to remember the name of the access functions
- Change of implementation: the implementation can be changed with no effect to users.
- Prevents corruption: users are not able to manipulate the data directly, hence incorrectly.
- Data encapsulation is a natural technique when implementing ADTs, due to the separation of the
specification from the implementation.

Definition of Data Hiding


Data hiding is a concept in object-oriented programming which confirms the security of members of
a class from unauthorized access. Data hiding is a technique of protecting the data members from
being manipulated or hacked from any other source. Data is the most sensitive and volatile content of
a program which if manipulated can result in an incorrect output and it also harms the integrity of the
data. Data hiding is controlled in Java with the help of access modifiers (private, public and
protected). The data which is public is accessible from outside the class hence if you want to hide

(BTEC HND in Computing/ Third Semester)


106
Data Structure & Algorithm 2020

your data or restrict it from being accessed from outside, declare your data private. Private data is
only accessible to the objects of that class only.

Let us understand data hiding with the help of an example. Suppose you declared
a CheckAccount class and you have a data member balance inside that class. Here, the balance of
an account is sensitive information. You may allow an outside application to check balance inside of
an account but, you won’t allow an outside application to alter the balance attribute. Thus declaring
the balance attribute private you would restrict the access to balance from an outside application.

An ADT may be implemented by specific data types or data structures, in many ways and in many
programming languages; or described in a formal specification language. ADTs are often
implemented as modules: the module's interface declares procedures that correspond to the ADT
operations, sometimes with comments that describe the constraints. This information hiding strategy
allows the implementation of the module to be changed without disturbing the client programs.

Benefit:

- Increases reliability
- The inner representation can be changed without affecting the rest of the program (as long as the
interface is preserved)
- Clients cannot directly manipulate the inner representation ⇒helps to guarantee the integrity of
objects
- Reduces the amount of code the programmer must be aware of • the code is easier to understand
- Makes errors easier to find
- Decreases the potential for name conflicts
- Hiding details of a module’s implementation from the rest of the system, so that those details can
be changed later without changing the rest of the system. It is necessary to have a mechanism
which makes visible from the outside only some of parts (typically operation declarations) of a
unit.

 Advantages of encapsulation and information hiding when using an ADT

(BTEC HND in Computing/ Third Semester)


107
Data Structure & Algorithm 2020

According to Donald Craig, data encapsulation, sometimes time referred to as data hiding
(information hiding), is the mechanism whereby the implementation details of a class kept hidden
from the user. The user can only perform a restricted set of operations on the hidden members of the
class by executing special function commonly called methods. The actions performed by the
methods are determined by the designer of the class, who must be careful not to make the methods
either overly flexible or too restrictive. This idea of hiding the details away from the user and
providing a restricted, clearly defined interface is the underlying theme behind concept of an abstract
data type.

Simply, you can understand data structure refers to the process of an object controlling outside
access to its internal data.

For instance, we provide the illustrated in the following diagram

Figure: The illustrated of data encapsulation

In the Figure, you can see the object's data is displayed in the center of the object. Data is
surrounded by functions. Other objects, called customers, can only see services and cannot
directly "view" data. (Remember programmers and designers using methodical terms, functions
and interchangeable operations.) We use service terminology to describe the set of methods that
objects Implementation can be called by other objects. If you think about an object that is an
instance of a class called File, that object is able to provide methods to open, close, and read a
file. These methods are services so we can say an instance of the File class provides services to
open, close, and read files. Furthermore, guest objects, who send messages to other objects, call
methods on other objects, only aware of the syntax of the method call. They do not know how

(BTEC HND in Computing/ Third Semester)


108
Data Structure & Algorithm 2020

this method is implemented. Therefore, in the case of the File example, the call object does not
know how the file object will open the file, it only knows that it will. This is like a managing
director of a business that requires a software developer to add some new services to the
company's website. The director doesn't care how the developer does it, they just want the
services added.

Classes provide encapsulation or hide information by access control. A class will grant or deny
access to its objects using public and private access assignments. The members openly define an
interface between a class and the user of that class. Any member can be accessed by any function
in a program. Objects can contain both public and private variables, public variables used with
the object's methods or interfaces. For example, I give a code in Java, shown in Figure below.

Figure: Code in Java

From the Figure above, the class Encapsulate Demo is encapsulated as the variables are declared
as private. The get methods like getAge() , getName() , getRoll() are set as public, these methods
are used to access these variables. The setter methods like setName(), setAge(), setRoll() are also
declared as public and are used to set the values of the variables.

(BTEC HND in Computing/ Third Semester)


109
Data Structure & Algorithm 2020

Returning to the basics of data encepsulation and hiding information, we will discuss the main
problem "data packaging and hidden information when using ADT". Based on the basic
knowledge about data encapsulation and information hiding, we easy to see the advantages of
them.

By keeping private data and providing well-defined service methods, the role of the object
becomes clear to other objects. This increases usability. Other objects are aware of the format to
send messages to objects providing public services. This is essentially a contract between two
objects. Invoker agrees to send messages in a specific format, including transferring any
necessary parameter information. The called object is agreeing to process the message and if
necessary, return a value in the specified format.

Shielding data means that the format of the private data needs to change because of some reason
the method call objects on the object whose data has changed will not need to change the format
they send the message to. For example, if we imagine that we need to change a data attribute
from float type to double. (Both represent real numbers, but dual types can often store larger
values.) If a guest object is updating the value directly, by changing the data type, you will also
need to change. code in the guest object. If you are dealing with large systems with hundreds of
classes, this kind of situation can quickly get out of hand with some necessary "door knocking"
classes.

From a software development perspective by having well-defined public services, it allows other
developers to quickly understand your code and reuse it in other applications. Using data
encapsulation when making changes but the interface must be the same. For example, to create a
buffer that can contain integers, design may choose to implement it with an array, which is not
from the user of the class. The designer then writes the push () and pop () method, needs to put
the numbers in the array, and removes them from the first version. These methods are made
accessible to the user. Tried to try the user created to access the array argument, a compile time
error will result. Should this presentation to resize the implementation to a linked list, sockets can
be changed with linked lists and push () and pop () methods rewritten so that (file name this)
change which file to register this. The code that the user has written to the buffer is still valid

(BTEC HND in Computing/ Third Semester)


110
Data Structure & Algorithm 2020

because it does not provide allowable access to the beginning of the first line. To sum up, the
advantages of data encapsulation and information hiding are:

1. Protecting an objects from unwanted access by client.


2. Allowing access to a level without revealing the complex details below that level
3. Reducing human errors.
4. Simplifies the maintenance of the application
5. Making the application easier to understand.

D2 Discuss the view that imperative ADTs are a basis for object orientation and, with
justification, state whether you agree.

(SearchMicroservices 2019) Object-oriented programming (OOP) is a programming language model


in which programs are organized around data, or objects, rather than functions and logic. An object
can be defined as a data field that has unique attributes and behavior. Examples of an object can
range from physical entities, such as a human being that is described by properties like name and
address, down to small computer programs, such as widgets. (SearchMicroservices 2019) This
opposes the historical approach to programming where emphasis was placed on how the logic was
written rather than how to define the data within the logic.

Abstract data type (ADT) is not necessarily an OOP concept. It is an older term to describe the
concepts of stack and queue in terms of their functionality, without describing the implementation.
An ADT is not a programming language, but it is implemented by programmer to solve the problem
or some class of problems.

- In OOP an ADT can be easily modeled as class:

- An instance as an object

- Data of ADT as properties or fields of class

- Operations as methods

- ADT is not OOP

(BTEC HND in Computing/ Third Semester)


111
Data Structure & Algorithm 2020

An abstract data type (ADT) is a model of a certain kind of data structure e.g. a stack. A stack has
push () and pop () operations and that have well-defined behavior. The abstract data type itself refers
to this model, not any implementation in any programming language. You could implement a stack in
an object-oriented language, but you could also implement it in a functional programming language.

Example of stack
- Piles of plates on dinner table
- Java compiler use post-fix notation for
translation of code
- Browser uses stack to maintain back
and forth movement of user on the
pages of a website.

Example of queue
- Phone answering machine following FIFO, first caller gets first receiving of call
- Luggage checking machine in airport
- Reception in wedding ceremony

From the beginning, before 1972, there was no concept of OOP and ADTs. Initially people began to
come up with a basic concept, after much discussion and discussion, the ADTs and OOP split in two
directions. ADTs revolve around data types and operators. For example, there is a Set <Integer>
function, which has two isEmpty and Add <Integer> methods. But when working with Java, it is
imperative to follow OOP, which has the concept of an interface set, which has two isEmpty and Add
<Interger> methods and has classes to implement this interface. This class has many properties such
as

1. Abstraction: This is the ability of the program to ignore or ignore certain aspects of

(BTEC HND in Computing/ Third Semester)


112
Data Structure & Algorithm 2020

information that it is working on directly, which means it has the ability to focus on the core
elements. Each object can complete internal tasks, report, change state and communicate with
other objects without knowing how the object performs the operation. Abstraction is also
expressed by the fact that an initial object may have some common characteristics, such as its
extension but the original object may not be the method to execute.

2. Encapsulation: This property does not allow users to change the state of the object. Only the
object's internal methods allow it to change its state. Allow the external environment to affect
the internal data of an object in any way completely dependent on the encoder. This is the
assurance of the integrity of the object.

3. Polymorphism: Expressed by sending messages. Send a comparable message to the function


of an object. The method used to reply to the message will depend on the object to which the
message is sent will respond differently. Programmers can define an attribute for a series of
objects close together, but when executed, they use the same name, automatically execute
each object according to the characteristics of each object without being mistaken. mixed.

4. Inheritance: This property allows the object to have available properties that other objects
have inherited. This attribute allows the object to share or expand existing allocations without
specifying.

There is a very similar nature of ADTs as encapsulation. Encapsulation says that only the Set class,
which has two methods, and you don't know how to do it.

Justification “Is an ADT being basic for OOP”


An object is depicted essentially by the names of the writings it gets (the names of its strategies in
the Simulate variation) and the qualities it typifies. The conduct of these techniques is variable; you
don't comprehend what to do in response to a message (a strategy call), in spite of the fact that it is
sensible to expect an arrival estimation of a given kind (which can at any rate be ensured in
Simulate-style OOP). The qualities on which it can act and the exercises that should be possible on

(BTEC HND in Computing/ Third Semester)


113
Data Structure & Algorithm 2020

them is called abstract data type. In the piece of the idea, there is no legacy. It requires parametric
polymorphism. Embodiment is vital yet there is no understanding of an article containing its very
own tasks; the activities ' semantics are a fundamental piece of the meaning of an ADT and can't be
changed. We can powerfully demonstrate ADTs in Smalltalk and its relatives, yet there is no real way
to characterize them.

The structure of Java was influenced by CLU-a language created by one of the people who gave
ADTs their name and authority definition, explicitly expected to permit ADT programming. Private
systems, last methods, generics and interfaces from Java empower you to construct stuff that are
viably ADTs. Despite everything it doesn't offer a particular thought of an ADT-it emerges from the
choices you make to characterize an abstract class or interface. C++ layouts were likewise affected
by CLU-however then C++ formats are not an article situated thought by any means, yet a
parametric polymorphism-based thought. In a short answer: no, although the idea affected the plan of
huge numbers of the later dialects connected to the article situated mark. It is likewise the crucial
idea driving dialects, for example, C++, C # and Java.

It is the basic idea behind languages like C++, C#, and Java. Since I was asked to answer, I will say
that I do not consider these OO languages. They are procedural languages with abstraction
capabilities. ADTs are not one of the basic ideas behind OOP. The basic ideas of OOP are
encapsulation (local retention, protection, and hiding of state-process), late-binding in all things, and
messaging. And I agree for the point “An ADT is the base of OOP” because OOP use the concept of
ADT. ADT provide the creation of instances with well-defined properties and behavior. The instance
that is declare by the ADT is object which is the basic concept of Object-Oriented Programming.
Hence, we can say that ADT is the base of OOP.

Conclusion: Can not say imperative ADTs are a basis for object orientation. ADTs revolve around
operators, so say ADTs are child of OOPs is not true, althought ADTs have some properties needed
for OOP.

Object-oriented programming and abstract data types can also be viewed as complementary
implementation techniques: objects are centered around the constructors of a data abstraction, while
abstract data types are organized around the operations

(BTEC HND in Computing/ Third Semester)


114
Data Structure & Algorithm 2020

I agree imperative ADT are a basis of oops because ADT allows the creation of instances with well-
defined properties and behavior. Abstraction allows you to collect instances of entities in groups in
which their common attributes must be taken into account. Example, Suppose we have to make a
program to deal with mobile and laptop. We can define the classes (entities) of mobile and laptop and
we will see they have much (but not all) functionality in common. It would be a mistake to derive
mobile from laptop or the other way around. What you need to do is to define a common abstract
base-class gadgets and derive both mobile and laptop from that class. Data abstraction is an
encapsulation of a data type and the subprograms that provide the operations for that type. Programs
can declare instances of that ADT, called an object. Object-oriented programming is based on this
concept. In object orientation, ADTs can be called classes.

Therefore, a class defines the properties of objects that are instances in an object-oriented
environment.ADT and Object oriented Programming are different concepts. OOPs use the concept of
ADT.

Conclusion of article:

In summary, this activity first describes ADT instead of the type and operation of ADT, and explains
why the stack called ADT in code. For example, it is attached to a screen capture of the coding. As a
benefit, I want to briefly explain what encapsulation is and hide the data. It also encloses the use of
encapsulation and data hiding in the form of Java code and describes how ADT maintains data
encapsulation and hiding. For the sake of differentiation, we have described the benefits and
examples of encapsulation, and how to facilitate, justify, and hide data.

(BTEC HND in Computing/ Third Semester)


115
Data Structure & Algorithm 2020

References
skfdjskdfjs, n.d. sdfsdf. [Online]
[Accessed 2014].

xgxdfd, n.d. xxfdxd. [Online]


[Accessed 2010].

Margaret Rouse, n.d. whatls.com. [Online]


Available at: https://whatis.techtarget.com/definition/structured-data
[Accessed 23 01 2019].

brilliant.org, n.d. brilliant.org. [Online]


Available at: https://brilliant.org/wiki/shortest-path-algorithms/
[Accessed 19 April 2019].

Dutta, M., Jul-Aug 2016. Basic Concept of Object Oriented and Procedure Oriented Programming.
International Journal of Information and Technology (IJIT), Volume 2(Issue 4), p. 2.

geeksforgeeks.org, n.d. geeksforgeeks.org. [Online]


Available at: https://www.geeksforgeeks.org/analysis-algorithms-big-o-analysis/
[Accessed 21 4 2019].

geeksforgeeks, n.d. geeksforgeeks. [Online]


Available at: https://www.geeksforgeeks.org/sorting-algorithms/
[Accessed 16 4 2019].

geeksforgeeks, n.d. geeksforgeeks.org. [Online]


Available at: https://www.geeksforgeeks.org/selection-sort/
[Accessed 17 4 2019].

Ishwar Saswade, 2015. Linked In. [Online]


Available at: https://www.linkedin.com/pulse/business-intelligence-concept-tools-techniques-ishwar-
saswade
[Accessed 01 04 2019].

(BTEC HND in Computing/ Third Semester)


116
Data Structure & Algorithm 2020

mk, r., 2017. Net-informations.com. [Online]


Available at: http://net-informations.com/faq/oops/encapsulation.htm
[Accessed 13 jan 2018].

Rouse, M., 2005. techtarget.com. [Online]


Available at: https://searchsqlserver.techtarget.com/definition/data-structure
[Accessed 15 4 2019].

Rouse, M., n.d. techtarget.com. [Online]


Available at: https://searchsoftwarequality.techtarget.com/definition/error-handling

S.Adamchik, V., 2009. cmu.edu. [Online]


Available at: https://www.cs.cmu.edu/~adamchik/15-121/lectures/Stacks%20and%20Queues/Stacks
%20and%20Queues.html
[Accessed 17 4 2019].

skfdjskdfjs, n.d. sdfsdf. [Online]


[Accessed 2014].

techopedia, n.d. techopedia. [Online]


Available at: https://www.techopedia.com/definition/28802/semi-structured-data

techopedia, n.d. techopedia. [Online]


Available at: https://www.techopedia.com/definition/13865/unstructured-data

xgxdfd, n.d. xxfdxd. [Online]


[Accessed 2010].

(BTEC HND in Computing/ Third Semester)


117
Data Structure & Algorithm 2020

(BTEC HND in Computing/ Third Semester)


118

You might also like