You are on page 1of 50

DATA STRUCTURES ALGORITHM

Table of Contents
Acknowledgement ............................................................................................................. 3
Introduction ...................................................................................................................... 4
L01: Examine abstract datatypes, concrete data structures and algorithms. ...................... 6
I have attached the flowchart and algorithm in the bitbucket as well.Error! Bookmark not
defined.
Abstract Data Types ................................................................................................................... 6
Stack ........................................................................................................................................ 10
Memory Stack.......................................................................................................................... 13
Queue ...................................................................................................................................... 16
Priority Queue ............................................................................................................................................ 17
Concrete Data Structure for Queue ........................................................................................................... 18
Compare of two sorting algorithms .......................................................................................... 19
Shortest Path Algorithms ......................................................................................................... 21
L02: Specify abstract datatypes and algorithms in a formal notation. .............................. 29
Software Stack ......................................................................................................................... 29
Encapsulation and Information hiding when using ADT ............................................................ 30
ADT are basis of OOP ............................................................................................................... 34
L03: Implement complex data structures and algorithm. ................................................. 35
Error handling and test report.................................................................................................. 35
................................................................................................................................................ 35
L04: Assess the effectiveness of data structures and algorithms....................................... 36
Asymbiotic Analysis ................................................................................................................. 37
Two ways in which efficiency of an algorithm can be measured ............................................... 38
Two Ways Algorithm................................................................................................................ 42
................................................................................................................................................ 46
Trade – Off ............................................................................................................................... 47
Heap Size vs. Throughput ........................................................................................................................... 47
Benefits of Using Implementation independent data structures............................................... 48
Conclusion ....................................................................................................................... 49
References ....................................................................................................................... 50

A. NIROJAN J/IT/18/12/01 1
DATA STRUCTURES ALGORITHM

Table of Figures
Figure 1:Flowchart for Palindrome .............................................................................. 6
Figure 2:Example for ADT ........................................................................................... 8
Figure 3:ADT Operation .............................................................................................. 9
Figure 4:Stack Operation .......................................................................................... 10
Figure 5:Difference stacks ........................................................................................ 11
Figure 6:Realworld stack example ............................................................................ 12
Figure 7:Example of memory stack ........................................................................... 13
Figure 8:Memory allocation ....................................................................................... 14
Figure 9:Memory stack and heap allocation ............................................................. 15
Figure 10:Queue realworld example ......................................................................... 16
Figure 11:Example of priority queue ......................................................................... 17
Figure 12:Queue operation ....................................................................................... 18
Figure 13:Shortestpath algorithm .............................................................................. 21
Figure 14:Example of shortest path .......................................................................... 22
Figure 15:Direct access and indirect access ............................................................. 30

A. NIROJAN J/IT/18/12/01 2
DATA STRUCTURES ALGORITHM

Acknowledgement

The success and final outcome of this assignment required a lot of guidance and assistance
from many people and I am extremely fortunate to have got this all along the completion of
my assignment work. Whatever I have done is only due to such guidance and assistance and
I would not forget to thank them.

I respect and thank Mr. B. Sabashan for giving me an opportunity to do this assignment on
time, I extremely grateful to him for providing such a nice support and guidance.

I am really grateful because I managed to complete this assignment within the time given by
my lecturer. This assignment cannot be completed without the effort and co-operation from
my class mates. I would like to express my gratitude to my friends and respondents for support
and willingness to spend some time with me.

A. Nirojan

A. NIROJAN J/IT/18/12/01 3
DATA STRUCTURES ALGORITHM

Introduction
The study of data structures, a fundamental component of a computer science education,
serves as the foundation upon which many other computer science fields are built. Some
knowledge of data structures is a must for students who wish to do work in design,
implementation, testing, or maintenance of virtually any software system.

The scope and presentation of material in Data Structures and Algorithms in Java provide
students with the knowledge necessary to perform such work. This book highlights three
important aspects of data structures. First, a very strong emphasis is placed on the connection
between data structures and their algorithms, including analyzing algorithms’ complexity.
Second, data structures are presented in an object-oriented setting in accordance with the
current design and implementation paradigm.

In particular, the information-hiding principle to advance encapsulation and decomposition is


stressed. Finally, an important component of the book is data structure implementation, which
leads to the choice of Java as the programming language. The Java language, an object-
oriented descendant of C and C++, has gained popularity in industry and academia as an
excellent programming language due to widespread use of the Internet.

Because of its consistent use of object-oriented features and the security of the language,
Java is also useful and natural for introducing data structures. Wide use of Java in application
programming and the object-oriented characteristics of the language, using Java to teach a
data structures and algorithms course, even on the introductory level, is well justified.

A. NIROJAN J/IT/18/12/01 4
DATA STRUCTURES ALGORITHM

L01

A. NIROJAN J/IT/18/12/01 5
DATA STRUCTURES ALGORITHM

L01: Examine abstract datatypes, concrete data structures


and algorithms.

Figure 1:Flowchart for Palindrome

A. NIROJAN J/IT/18/12/01 6
DATA STRUCTURES ALGORITHM

Algorithm for Palindromes

Step 1: Input a word.

Step 2: Convert the word into character.

Step 3: Push the word to stack.

Step 4: Enqueue the word into queue.

Step 5: pop the word and at the same time dequeue the word from stack and queue.

Step 6: Check whether the pop character and dequeued character is same or not.

Step 7: If it correct it Is a palindrome

Step 8: End

A. NIROJAN J/IT/18/12/01 7
DATA STRUCTURES ALGORITHM

Abstract Data Types

As a programmer before the program is written the programmer need to have an idea of how
accomplish the task being completed by program. The behavior of the program is more
important than gears mechanism to accomplishing it.

The implementation decides that which data structure will be used to make execution most
efficient in terms of time and space. For an example, if an item needed to accomplish the
specific task, the item is specified in terms of operations performed on it rather than in terms
of its inner structure.

Data structure is used to denote the specific way of organizing data for particular types of
operations. The data stored in computer memory we will do it by formulating abstract
mathematical models of particular classes of data structures or data types which have
common features in it. These called as abstract data types.

Abstract data types are simplifying development lifecycle and to create reusable code is well
established. An ADT is a collection of data together with specification of a set of algorithms on
data.
When a program needed data operations that are not directly supported by language then
need to create an own ADT.

Figure 2:Example for ADT

A. NIROJAN J/IT/18/12/01 8
DATA STRUCTURES ALGORITHM

Example of ADT in Real World

Data: Water

Operation: chill, cube, is Empty.

Data Structure: The internal structure of dispenser

Walls: made of steel\

The ADT is like using a vending machine.

Figure 3:ADT Operation

A. NIROJAN J/IT/18/12/01 9
DATA STRUCTURES ALGORITHM

Stack
Stack allow to access only one data item that is the last item inserted and if remove last item
then you will get next to last item inserted and so on. It also handy aid for algorithm that applied
on some complex data structures. Stack is a LIFO structure that is first in/last out.

Stacks are the simplest of all data structures, yet they are also among the most important, as
they are used in a host of different applications, and as a tool for many more sophisticated
data structures and algorithms. Formally, a stack is an abstract data type (ADT) that supports
the following two update methods:

• Push () – Put the element on top of the stack.

• Pop () – Take the topmost element from the stack.

• is Empty () – Check if the stack is empty or not.

• Is Full () – Check if the stack is full or not.

• Peek () – Object at top of stack without removing or modifying it from stack.

Figure 4:Stack Operation

In this pushing number 10 in an empty stack, the stack contains only one number. After push
number 5 on stack, the number is placed on top of 10 and when popping operation is executed
5 is removed from stack because it arrived after 10 and then 10 left on stack.

After pushing 15 and 7, the most top element is 7 and after removed number 7 when executing
popping operation done and after stack contains 10 at bottom and 15 above it. The stack is
very useful in situations when data have to be stored and then retrieved in reverse order.

A. NIROJAN J/IT/18/12/01 10
DATA STRUCTURES ALGORITHM

Java.util. stack Class

Concrete class named java.util.stack that implements the LIFO semantics of a stack.
However, Java’s Stack class remains only for historic reasons, and its interface is not
consistent with most other data structures in the Java library. In fact, the current
documentation for the Stack class recommends that it not be used, as LIFO
functionality (and more) is provided by a more general data structure known as a
double-ended queue.

I have provides a side-by-side comparison of the interface for our stack ADT and the
java.util.Stack class.

Figure 5:Difference stacks

A. NIROJAN J/IT/18/12/01 11
DATA STRUCTURES ALGORITHM

Stack with Real World Example

Figure 6:Realworld stack example

In this you can identify that what is happen and the letters in bottom would not examine
for months, bills they come over due this is the main problem when using stack in real
world.

A. NIROJAN J/IT/18/12/01 12
DATA STRUCTURES ALGORITHM

Memory Stack

Memory Stack is a memory usage mechanism that allows the system memory to be
used as temporary data storage that behaves as a first-in, last-out buffer. One of the
essential elements of stack memory operation is a register called the stack pointer.
The stack pointer is adjusted automatically each time a stack operation is carried out.

In common terms, storing data to the stack is called pushing (using the PUSH instruction) and
restoring data from the stack is called popping (using the POP instruction). Depending on
processor architecture, some processors perform storing of new data to stack
memory using incremental address indexing and some use decrement address indexing.

Figure 7:Example of memory stack

A. NIROJAN J/IT/18/12/01 13
DATA STRUCTURES ALGORITHM

The current contents of the registers used by the calling program are stored onto the
stack memory using a PUSH operation, and at the end of the function, the data on the
stack memory is restored to the registers using a POP operation. Typically, each
register PUSH operation should have a corresponding register POP operation,
otherwise the stack pointer will not be able to restore registers to their original values.

Figure 8:Memory allocation

It is important to set up sufficient stack memory for your project. Two memory access
instructions are dedicated to stack memory accesses. The PUSH instruction is used
to decrement the current stack pointer and store data to the stack. The POP instruction
is used to read the data from the stack and increment the current stack pointer. Both
PUSH and POP instructions allow multiple registers to be stored or restored.

A. NIROJAN J/IT/18/12/01 14
DATA STRUCTURES ALGORITHM

Key Features of Memory Stack

• It automatically allocated and deallocated when method finishes execution.

• This memory is thread safe as each thread operates in its own stack.

• If memory is full java throws java.lang.StackOverFlowError.

Information about a running program is stored in computer memory. Every interface,


class, object and running method has a separate region of memory to keep track of
variable values and other related information.

Figure 9:Memory stack and heap allocation

A. NIROJAN J/IT/18/12/01 15
DATA STRUCTURES ALGORITHM

Queue

Queue is a data structure that is somewhat like a stack, except that in a queue the first
item inserted is the first to be removed First-In-First-Out while in a stack, as we’ve
seen, the last item inserted is the first to be removed. A queue works like the line at
the movies: The first person to join the rear of the line is the first person to reach the
front of the line and buy a ticket. The last person to line up is the last person to buy a
ticket.

Figure 10:Queue realworld example

Enqueue - The enqueue () method assumes that the queue is not full. We don’t show
it in main (), but normally you should call enqueue () only after calling isFull () and
getting a return value of false. It will insert the element in to the rear of the queue.

Dequeue - The dequeue () method assumes that the queue is not empty. You should
call isEmpty () to ensure this is true before calling dequeue (), or build this error-
checking into dequeue (). It will remove the element on the front.

Peek - The peek () method is straightforward: It returns the value at front. Some
implementations allow peeking at the rear of the array as well; such routines are called
something like peekFront () and peekRear () or just front () and rear ().

isEmpty, isFull - The isEmpty (), isFull (), and size () methods all rely on the number
of items field, respectively checking if it’s 0, if it’s maxSize, or returning its value.

A. NIROJAN J/IT/18/12/01 16
DATA STRUCTURES ALGORITHM

Priority Queue

It is a more specialized data structure than a stack or a queue. It’s a useful tool in a
surprising number of situations. Like an ordinary queue, a priority queue has a front
and a rear, and items are removed from the front. However, in a priority queue, items
are ordered by key value so that the item with the lowest key is always at the front.
Items are inserted in the proper position to maintain the order.

Figure 11:Example of priority queue

A. NIROJAN J/IT/18/12/01 17
DATA STRUCTURES ALGORITHM

Concrete Data Structure for Queue

A FIFO data structure is one in which data is accessed and removed in the order in
which it was inserted. The queue data structure ensures that you come out in the order
in which you joined the line/queue. For example, if an element was inserted into the
queue data structure, it would have to wait until it reaches the front of the queue before
it can be removed.

Eg 1: If you are in fifth person in line, this means you will be gets on after first four people in
front of you have gone. You need to wait that until the person in front of you is gotten 0. Like
that items in the queue are dequeued in order that they enter the queue.

Eg 2: We are gathering data from a device that is sending us data packets consistently via
the TCP/IP protocol. And all of a sudden, the connection is becoming unstable for 10 seconds.
The data that has not been sent due to connection loss can be stored in a queue so that when
the connection is established after 10 seconds, it shoots the packet in the order of occurrence
and not in some random order.

Figure 12:Queue operation

A. NIROJAN J/IT/18/12/01 18
DATA STRUCTURES ALGORITHM

Compare of two sorting algorithms


Sorting is the procedure of ordering list of elements in ascending or descending with the help
of key value in specific order. Many sorting algorithms have been designed and are being
used.

Bubble Sort Algorithm

Even in our daily life, children are confronted with problems like sorting their things, like toys,
in some order. Hence, they learn the problem of sorting even before learning anything about
computing or arithmetic.

Algorithm uses a method of comparison to execute its sorting operations. Pairs of values are
compared and the necessary swapping done according to the order required. The larger
element is constantly compared and bubbled to its right position in the array.

There is a repetition of the passes through the list is sorted and no more swaps are needed.
It is a simple algorithm but it lacks in efficiency when the given input data set is large. There
is one major advantage that bubble sort has over the other better performing algorithms is that
it has the ability to detect whether the given list is trivially sorted or not.

Strength

• It is easy to understand
• Easy to implement
• No demand for large amounts of memory
• Once sorted, data is available for processing

The algorithm executes in a time directly proportional to the size of the array. The worst-case
scenario of its operation occurs when the array needs to be 'reverse sorted'.

A. NIROJAN J/IT/18/12/01 19
DATA STRUCTURES ALGORITHM

Selection Sort Algorithm

Selection sort is noted for its simplicity and even performs better than many complicated
algorithms in certain situations especially where auxiliary memory is limited as it is an in-place
comparison sort. It starts by selecting the minimum value in the given list, as the name
suggests. After selecting the value, it swaps with the value in the first position of the list. In this
way, the given list is divided into two parts consisting of the sub-list of items already sorted
from left to right and the other sub-list of items remaining to be sorted. It repeats this step
iteratively and places each element as its proper position.

Suppose an array A with n elements in memory. The selection sort algorithm for sorting an
array A works as follows.

i) To find the smallest element in the list and put in the first position.

ii) To find the second smallest element in the list and put in the second position
and so on.

Advantages:

1. Improves the performance of bubble sort and also slow.


2. Unstable but can be implemented as a stable sort.
3. Quite slow for large amount of data.

Comparison

Bubble Sort - Adjacent element is compared and swapped.

Selection Sort - Largest element is selected and swapped with the last element.

Bubble Sort – Inefficiency

Selection Sort – Improved efficiency as compared to bubble sort.

A. NIROJAN J/IT/18/12/01 20
DATA STRUCTURES ALGORITHM

Shortest Path Algorithms


Shortest paths are very useful problem-solving model for maps, robot navigation, texture
mapping, urban traffic planning, sub routine for advanced algorithms, routing of
telecommunication messages, network routing protocols and etc.

Figure 13:Shortestpath algorithm

A. NIROJAN J/IT/18/12/01 21
DATA STRUCTURES ALGORITHM

Dijkstra’s Algorithm

Dijkstra developed this algorithm in 1956. He was 26 at the time, working on his PhD in the
Netherlands. Dijkstra’s algorithm uses a greedy method, the algorithm, computers for vertex
v the distance of v from the start vertex s, that is the weight of shortest path between s and v.

Grow set of nodes whose shortest distance has been computed, nodes are not in set will have
a best distance so far and a priority queue will turn out to be useful for efficiency.

It can also be used for finding costs of shortest paths from a single vertex to a single
destination vertex by stopping the algorithm once the shortest path to the destination vertex
has been determined. For example, if the vertices of the graph represent cities and edge path
costs represent driving distances between pairs of cities connected by a direct road, Dijkstra's
algorithm can be used to find the shortest route between one city and all other cities.

Dijkstra’s Idea

1. Shortest distance from s to all nodes initially “unsettled”.

2. Shortest distance to s is zero. Tentative distance to others is ∞.

3. Put all nodes in queue ordered by tentative distance from s.

4. Take out nearest unsettled node, x. Settle its distance from s.

5. For each unsettled immediate neighbor y of x.

6. If going from s to y through x is shorter than shortest path through settled nodes,
update tentative distance to y.

7. Repeat from step 4, until distance to destination is settled.

Figure 14:Example of shortest path

A. NIROJAN J/IT/18/12/01 22
DATA STRUCTURES ALGORITHM

Example of Dijkstra’s Algorithm:

A. NIROJAN J/IT/18/12/01 23
DATA STRUCTURES ALGORITHM

A. NIROJAN J/IT/18/12/01 24
DATA STRUCTURES ALGORITHM

Final Result of the above Dijkstra’s shortest path

A. NIROJAN J/IT/18/12/01 25
DATA STRUCTURES ALGORITHM

Floyd - Warshall Algorithm

It is a graph analysis algorithm for finding shortest paths in a weighted graph with positive or
negative edge weights (but with no negative cycles, see below) and also for finding transitive
closure of a relation R.

A single execution of the algorithm will find the lengths (summed weights) of the shortest paths
between all pairs of vertices, though it does not return details of the paths themselves. The
algorithm is an example of dynamic programming.

It was published in its currently recognized form by Robert Floyd in 1962. However, it is
essentially the same as algorithms previously published by Bernard Roy in 1959 and also by
Stephen Warshall in 1962 for finding the transitive closure of a graph. The modern formulation
of Warshall's algorithm as three nested for-loops was first described by Peter Ingerman, also
in 1962.

The Floyd–Warshall algorithm compares all possible paths through the graph between each
pair of vertices. The Floyd–Warshall algorithm typically only provides the lengths of the paths
between all pairs of vertices. With simple modifications,

it is possible to create a method to reconstruct the actual path between any two endpoint
vertices. While one may be inclined to store the actual path from each vertex to each other
vertex, this is not necessary, and in fact, is very costly in terms of memory. For each vertex,
one need only store the information about the highest index intermediate vertex one must
pass through if one wishes to arrive at any given vertex.

Example

A. NIROJAN J/IT/18/12/01 26
DATA STRUCTURES ALGORITHM

The final algorithm executed is here:

A. NIROJAN J/IT/18/12/01 27
DATA STRUCTURES ALGORITHM

L02

A. NIROJAN J/IT/18/12/01 28
DATA STRUCTURES ALGORITHM

L02: Specify abstract datatypes and algorithms in a formal


notation.

Software Stack

A stack can be easily implemented either through an array or a linked list. What
identifies the data structure as a stack in either case is not the implementation but the
interface: the user is only allowed to pop or push items onto the array or linked list,
with few other helper operations. The following will demonstrate both implementations,
using pseudocode.

Some languages, such as Perl, LISP, JavaScript and Python, make the stack
operations push and pop available on their standard list/array types. Some languages,
notably those in the Forth family are designed around language-defined stacks that
are directly visible to and manipulated by the programmer.

Applications of Stack

• Calculators – They are employing reverse Polish notation use a stack structure to hold
values. Expressions can be represented in prefix, postfix or infix notations and
conversion from one form to another may be accomplished using a stack.

• Compilers - use a stack for parsing the syntax of expressions, program blocks etc.
before translating into low level code. Most programming languages are context-free
languages, allowing them to be parsed with stack based machines.

• Backtracking - Consider a simple example of finding the correct path in a maze. There
are a series of points, from the starting point to the destination. We start from one point.
To reach the final destination, there are several paths. Suppose we choose a random
path. After following a certain path, we realize that the path we have chosen is wrong.
So, we need to find a way by which we can return to the beginning of that path. This
can be done with the use of stacks. With the help of stacks, we remember the point
where we have reached. This is done by pushing that point into the stack.

A. NIROJAN J/IT/18/12/01 29
DATA STRUCTURES ALGORITHM

Encapsulation and Information hiding when using ADT

In the direct access, when information is realized using the direct access technique, we say
that the functionality and implementation are coupled together and in the indirect access,
when the information is realized using the indirect access technique and we say that the
functionality and implementation are decoupled.

Figure 15:Direct access and indirect access

A. NIROJAN J/IT/18/12/01 30
DATA STRUCTURES ALGORITHM

Direct Access

Direct Access – The variables have public access and they are directly accessible to the user.

public class BankAccount


{

public double balance;

The variable access of balance can be accessed directly from anywhere due to public
access specifier.

public class MyProgram


{
public static void main( String[] args )
{

BankAccount stu1 = new BankAccount(123, "John", 1000.0);

stu1.balance = stu1.balance + 500;


}
}

A. NIROJAN J/IT/18/12/01 31
DATA STRUCTURES ALGORITHM

Indirect Access

The variable have private access and they indirectly accessible to the user through public
methods.

public class BankAccount


{
private double balance;

public double getBalance()


{
return balance;
}

public void putBalance(double x)


{
balance = x;
}
}

Variable balance must be accessed indirectly through the methods getBalance () and
putBalance ().

public class MyProgram


{
public static void main( String[] args )
{
BankAccount stu1 = new BankAccount(123, "John", 1000.0);
double x;

x = stu1.getBalance();

stu1.putBalance(x + 500);
}
}

A. NIROJAN J/IT/18/12/01 32
DATA STRUCTURES ALGORITHM

• Effect of the direct data access on these 2 aspects:

When information is realized using the direct access technique, we say that
the functionality and implementation are coupled together.

• Effect of the indirect data access on these 2 aspects:

When information is realized using the indirect access technique, we say that
the functionality and implementation are decoupled

Information hiding and Abstract Data Type

• Information hiding = "hide" the variables from the users so they cannot access
the variable directly. This is done by having private access variables and
user must make use of public access methods to gain access to the variables.

• Abstract Data Type (ADT) = a data storage structure that is defined by


the functionality and it is defined by what kind of information can you obtain
from the ADT. The ADT will provide a number of public access methods to
provide the functionalities and to ensure data integrity the variables used to
store the information are protected by private access permission.

A. NIROJAN J/IT/18/12/01 33
DATA STRUCTURES ALGORITHM

ADT are basis of OOP

Abstract data types are often called user-defined data types, because they allow programmers
to define new types that resemble primitive data types. Just like a primitive type INTEGER
with operations +, −, ∗, etc., an abstract data type has a type domain, whose representation
is unknown to clients, and a set of operations defined on the domain.

The advantages gained from the application ADTs and OOP are well demonstrated in many
areas of computer science. The interest in applying ADTs and OOP to scientic computing is
rapidly growing. Most of the literature contributions on object-oriented numeric are concerned
with specic numerical algorithms, often involving complicated data structures

Object-oriented programming involves the construction of objects which have a collection of


methods, or procedures, that share access to private local state. Objects resemble machines
or other things in the real world more than any well-known mathematical concept.

ADT is at the core of OOP Abstraction principle, which should be supplemented by


Polymorphism and Inheritance. One might say that ADT (Abstraction) is at the very base of
OOP and the rest of the principles stem from it to supplement it.

Abstract datatype (ADT) is not necessarily an OOP concept. It is an older term to describe the
concepts of for example Stack and Queue in terms of their functionality, without describing the
implementation.

The abstract data type (ADT) itself refers to this model, not any particular implementation in
any particular programming language or paradigm. Could implement a Stack in an object-
oriented language, but you could also implement it in a functional programming language.

A. NIROJAN J/IT/18/12/01 34
DATA STRUCTURES ALGORITHM

L03: Implement complex data structures and algorithm.

Error handling and test report

A. NIROJAN J/IT/18/12/01 35
DATA STRUCTURES ALGORITHM

Test Cases Input


Result Criteria

Waiter or chef needs to select


Welcome Option
who are they Displays the drink or food
Passed
option

Waiter needs to select which item Displays the available foods


Waiter Selection Passed
customer need or available drinks

User selected food option after Displays only the foods


Waiter select food Passed
that available foods are shown up items
Displays your item is not
Waiter inputted
unknown item
User inputted non available item available please select
Passed another

Waiter enter all After collecting wanted items


the items waiter push the order to chef Alert goes to kitchen with
Passed
table no
Displays please enter the
Before collecting wanted items Passed
table number
Waiter forgot to
enter which table
waiter needs to enter the table
number

A. NIROJAN J/IT/18/12/01 36
DATA STRUCTURES ALGORITHM

L04: Assess the effectiveness of data structures and


algorithms.
Asymbiotic Analysis
Asymptotic Analysis is not perfect, but that’s the best way available for analyzing algorithms.
For example, say there are two sorting algorithms that take 1000nLogn and 2nLogn time
respectively on a machine.

The main idea of asymptotic analysis is to have a measure of efficiency of algorithms that
doesn’t depend on machine specific constants, and doesn’t require algorithms to be
implemented and time taken by programs to be compared. Asymptotic notations are
mathematical tools to represent time complexity of algorithms for asymptotic analysis.

It is a well-established fact that merge sort runs faster than insertion sort. Using asymptotic
analysis we can prove that merge sort runs in O(nlogn) time and insertion sort takes O(n^2).
It is obvious because merge sort uses a divide-and-conquer approach by recursively solving
the problems whereas insertion sort follows an incremental approach.

Both of these algorithms are asymptotically same. So, With Asymptotic Analysis, we can’t
judge which one is better as we ignore constants in Asymptotic Analysis. Also, in Asymptotic
analysis, we always talk about input sizes larger than a constant value. It might be possible
that those large inputs are never given to your software and an algorithm which is
asymptotically slower, always performs better for your particular situation. So, you may end
up choosing an algorithm that is Asymptotically slower but faster for your software.

Worst Case Analysis

Calculate upper bound on running time of an algorithm. We must know the case that
causes maximum number of operations to be executed. For Linear Search, the worst
case happens when the element to be searched (x in the above code) is not present
in the array. When x is not present, the search () functions compares it with all the
elements of arr [] one by one. Therefore, the worst-case time complexity of linear
search would be Θ(n).

Average Case Analysis

Take all possible inputs and calculate computing time for all of the inputs. Sum all the
calculated values and divide the sum by total number of inputs. We must know distribution of
cases. For the linear search problem, let us assume that all cases are uniformly distributed.
So, we sum all the cases and divide the sum by (n+1). Following is the value of average case
time complexity.

A. NIROJAN J/IT/18/12/01 37
DATA STRUCTURES ALGORITHM

Best Case Analysis

calculate lower bound on running time of an algorithm. We must know the case that
causes minimum number of operations to be executed. In the linear search problem,
the best case occurs when x is present at the first location. The number of operations
in the best case is constant (not dependent on n). So, time complexity in the best case
would be Θ (1).

Most of the times, we do worst case analysis to analyze algorithms. In the worst
analysis, we guarantee an upper bound on the running time of an algorithm which is
good information.

The average case analysis is not easy to do in most of the practical cases and it is
rarely done. In the average case analysis, we must know (or predict) the mathematical
distribution of all possible inputs. The Best-Case analysis is bogus. Guaranteeing a
lower bound on an algorithm doesn’t provide any information as in the worst case, an
algorithm may take years to run.

Two ways in which efficiency of an algorithm can be measured

Time Efficiency – A measure of amount of time for an algorithm to execute

Space Efficiency – A measure of amount of memory needed for an algorithm to execute.

Complexity Efficiency – A study of algorithm performance.

Asymbiotic Dominance – Comparison of cost functions when n is large.

There are several ways to say that an algorithm is efficient or not. The mostly used ways are
time complexity and space complexity analysis. Time complexity says, for a given input size
n, how much time the algorithm will take to produce the desired result. On the other hand,
space complexity tells how much space it will consume if I run my code. There are several
notations to denote time complexity.

A. NIROJAN J/IT/18/12/01 38
DATA STRUCTURES ALGORITHM

Bottom line is -- if you have another algorithm to try, and you don't want to do BigO analysis
for both -- run each on small sets of data and compare. If your data is HUGE -- then BigO
analysis is the best way to go.

Three ways of Asymbiotic notations to measure the growth of any algorithm, as input
increases.

• Big-O Notation
• Big Omega
• Bit Theta

Big-O Notation

This can be amortized to O(n). Since the degree of polynomial is ‘n’ it is also called linear time
complexity. It is machine independent and grows linearly or in direct proportion to number
Fibonacci numbers ‘n’ to be calculated. An algorithm which is even independent of the data
set, is said to run in constant time and in denoted by O (1). For example, adding two numbers.
Order of magnitude/asymptotic categorization eliminates hardware from consideration and
expresses efficiency in terms of data size, N.

Example:

5n + 7 <= 5n + n for n >= 7


<= 6n

Big-O Categories

Function Big-O Name


1 O(1) constant
log n O(log n) logarithmic
n O(n) linear
n log n O(n log n) n log n
n2 O(n2) quadratic
n3 O(n3) cubic
2n O(2n) exponential
n! O(n!) factorial

A. NIROJAN J/IT/18/12/01 39
DATA STRUCTURES ALGORITHM

Example:

package dsa.samples;

public class Demo {

public static void main(String[] args) {

int n = 1000;
System.out.println("Hey - your input is: " + n);
System.out.println("Hmm.. I'm doing more stuff with: " + n);
System.out.println("And more: " + n);

Big Omega Notation

O - notation is used to represent the upper bound (worst case) run time of an algorithm whereas
Ω is used to represent the lower bound or the best-case scenario. For the n-Fibonacci numbers
example, if n = 2, our function runs in a constant time which is the best case represented as f(n)
= Ω (1).

A. NIROJAN J/IT/18/12/01 40
DATA STRUCTURES ALGORITHM

Big Theta Notation

Upper bound and lower bound of an algorithm are equal and both best case and worst-case
scenarios take the same amount of time within a constant factor, the complexity of that
algorithm is represented by ϴ notation.

Example:

package dsa.samples;

public class Demo {

public static void main(String[] args) {


int max;
int[] array;
max = array[0];
for (int i = 1; i < n; ++i){
if(array[i] > max) {
max = array[i];
}
}
}

A. NIROJAN J/IT/18/12/01 41
DATA STRUCTURES ALGORITHM

Two Ways Algorithm

Character Stack

package bcas.dsa.stack.pallindromes;

public class CharStack {


private int maxsize;
String reverse ="";
char[] stackArray = reverse.toCharArray();
private int top;

public CharStack(int m) {
maxsize = m;
stackArray = new char[m];
top = -1;

public void push(char j) {


stackArray[++top] = j;

public char pop() {


return stackArray[top--];

public char peek() {


return stackArray[top];

public boolean isempty() {


return (top == -1);

public boolean isfull() {


return (top == maxsize - 1);

public void isfull1() {


// { if (top== maxsize-1)?0;}

A. NIROJAN J/IT/18/12/01 42
DATA STRUCTURES ALGORITHM

public void printarray() {


for (char l : stackArray) {
System.out.println(stackArray);

}
}

Character Queue

package bcas.dsa.stack.pallindromes;

public class CharQueue {

private int capacity;


char[] arr = new char[capacity];
int size = 0;;
int top = -1;
int rear = 0;;
int nItems = 0;

public void enque(char pushedElement) {

if (top < capacity - 1) {

top++;
arr[top] = pushedElement;
nItems++;

} else {

System.out.println("Overflow");
}
}

public int disque() {

A. NIROJAN J/IT/18/12/01 43
DATA STRUCTURES ALGORITHM

if (top >= rear) {

rear++;
nItems--;

} else {

System.out.println("Underflow");
}

return capacity;

public boolean isEmpty() {


return (nItems == 0);

public boolean isFull() {


return (top == capacity);

A. NIROJAN J/IT/18/12/01 44
DATA STRUCTURES ALGORITHM

package bcas.dsa.stack.pallindromes;

import java.util.Scanner;

public class PalindromeDemo {

public static void main(String[] args) {

String popString = “”;


String DequeueString = &quot;&quot;;
Scanner scan = new Scanner(System.in);
System.out.println(&quot;enter the value&quot;);
String read = scan.nextLine();
String name = read.toUpperCase();
System.out.println(&quot;your value is : &quot; + name);
MyStack reverseStack = new MyStack(10);
MyQueue queue = new MyQueue(10);

for (int i = 0; i &lt; name.length(); i++) {


reverseStack.push(name.charAt(i));

}
for (int i = 0; i &lt; name.length(); i++) {
queue.enqueue(name.charAt(i));
}

while (!reverseStack.isempty() &amp;&amp; !queue.isEmpty()) {

popString = popString +Character.toString(reverseStack.pop());

DequeueString=DequeueString + Character.toString(queue.dequeue
());
}
System.out.println();

if (popString.equals(name) && DequeueString.equals(name))


{
System.out.println(name +” is a palindrome”);

} else {
System.out.println(name + “is not palindrome”);
}

}
}

A. NIROJAN J/IT/18/12/01 45
DATA STRUCTURES ALGORITHM

A. NIROJAN J/IT/18/12/01 46
DATA STRUCTURES ALGORITHM

Trade – Off
Identifying and closely considering trade-offs is the last step of the decision process. It is useful
at this point to recall that the overall purpose of the process is not to find some objectively
defined optimal solution, but to find the best solution that is supportable at some level by all
the decision participants. In most cases, this support hinges on participants’ awareness and
acceptance of various trade-offs.

Perceptual decision making has been successfully modeled as a process of evidence


accumulation up to a threshold. In order to maximize the rewards earned for correct responses
in tasks with response deadlines, participants should collapse decision thresholds dynamically
during each trial so that a decision is reached before the deadline. This strategy ensures on-
time responding, though at the cost of reduced accuracy, since slower decisions are based
on lower thresholds and less net evidence later in a trial.

Functional approaches emphasize Verifiability, Testability, and Scalability at the expense of


Modifiability, Extensibility, and in some cases Understandability. Procedural approaches
emphasize Modifiability, Understandability, and Expediency at the expense of Testability,
Verifiability, and if you're not careful Maintainability. Object-oriented approaches emphasize
Testability, Modifiability, and Scalability at the expense of Extensibility, Expediency, and if you
have a poor design Understandability.

Aspect-oriented approaches emphasize Modifiability, Extensibility, and Expediency at the


expense of Testability, Verifiability, and arguably Understandability. So, which one do we want
to use? Which approach is best? The one that best fits your use case and priorities, of course.

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.

Heap Size vs. Throughput


A large heap reduces the garbage collection frequency and the negative impact of
fragmentation, thus improving the throughput of the application. On the other hand, a large
heap increases the memory footprint of the Java process.

A. NIROJAN J/IT/18/12/01 47
DATA STRUCTURES ALGORITHM

Benefits of Using Implementation independent data structures

Representation Independence in the most of the program becomes independent of the


abstract data type's representation, so that representation can be improved without breaking
the entire program. Modularity is with representation independence, the different parts of a
program become less dependent on other parts and on how those other parts are
implemented.

Interchangeability of Parts are different implementations of an abstract data type may have
different performance characteristics. With abstract data types, it becomes easier for each
part of a program to use an implementation of its data types that will be more efficient for that
particular part of the program.

Java's standard libraries supply several different implementations of its Map data type.
The Tree Map implementation might be more efficient when a total ordering on the keys can
be computed quickly but a good hash value is hard to compute efficiently.
The HashMap implementation might be more efficient when hash values can be computed
quickly and there is no obvious ordering on keys. The part of a program that creates a Map can
decide which implementation to use. The parts of a program that deal with a created Map don't
have to know how it was implemented; once created, it's just a Map.

If it weren't for abstract data types, every part of the program that uses a Map would have to
be written twice, with one version to deal with Tree Map implementations and another version
to deal with HashMap implementations.

Data structures allow information storage on hard disks and it provides means for
management of large dataset such as databases or internet indexing services. It is necessary
for design of efficient algorithms and allows safe storage of information on a computer. The
information is then available for later use and can be used by multiple programs. Additionally,
the information is securing and cannot be lost and it allows the data use and processing on a
software system. Allows easier processing of data, it Using internet, we can access the data
anytime from any connected machine (computer, laptop, tablet, phone, etc.)

A. NIROJAN J/IT/18/12/01 48
DATA STRUCTURES ALGORITHM

Conclusion

Really, I am so happy in completing this assignment because I have learned a lot by doing
this assignment and also, whatever the things I missed to understand in the lecturers now with
the help of assignment I have understood. And also, now I have the confident in developing
the software system an also I have the experience in developing a software system. Mainly I
have analysis about test cases for the source code and it was wonderful because they found
me some mistakes on my assignment. It was good experience.

A. NIROJAN J/IT/18/12/01 49
DATA STRUCTURES ALGORITHM

References
Alexander, 2010. Git Hub. [Online]
Available at: https://github.com/dieuph/
[Accessed 10 03 2019].
Anon., 2013. Geeksforgeeks. [Online]
Available at: https://www.geeksforgeeks.org/analysis-of-algorithms-set-2-asymptotic-
analysis/
[Accessed 10 09 2019].
Anon., 2014. Baeldung. [Online]
Available at: https://www.baeldung.com/java-algorithm-complexity
[Accessed 20 09 2019].
Anon., 2014. web.cs.ucla.edu. [Online]
Available at: http://web.cs.ucla.edu/~palsberg/paper/toplas06.pdf
[Accessed 15 02 2019].
Anon., 2015. Research Gate. [Online]
Available at:
https://www.researchgate.net/publication/264526768_Speed_Accuracy_Trade-
off_Under_Response_Deadlines
[Accessed 26 09 2019].
Anon., 2015. xenonstack. [Online]
Available at: https://www.xenonstack.com/insights/what-is-test-driven-development
[Accessed 20 03 2019].
Anon., 2017. Coursehero. [Online]
Available at: https://www.coursehero.com/tutors-problems/Computer-
Science/18322262-Evaluate-three-benefits-of-using-implementation-independent-
data-struc/
[Accessed 15 09 2019].
Anon., 2018. Coursehero. [Online]
Available at: https://www.coursehero.com/file/42331415/Assignment-2-data-
structure-Algorithmdocx/
[Accessed 24 09 2019].
Anon., 2018. Princeton. [Online]
Available at: http://sce2.umkc.edu/BIT/burrise/pl/abstraction-info-hiding-
encapsulation/
[Accessed 30 09 2019].
Anon., 2019. Oracle. [Online]
Available at: http://www.dba-oracle.com/t_object_encapsulation_abstract.htm
[Accessed 01 10 2019].
Noble, J., 2019. homepages.ecs. [Online]
Available at: http://homepages.ecs.vuw.ac.nz/~kjx/papers/classify.pdf
[Accessed 19 02 2019].

A. NIROJAN J/IT/18/12/01 50

You might also like