Docsity

Fundamentals of Algorithm Analysis: Efficiency, Asymptotic Notations, and Problem Solving, Study notes of Design and Analysis of Algorithms

Toggle sidebar
bg1
Program
Name
BCA
Semester
V
Course Title
Design and Analysis of Algorithm (Theory)
Course Code:
DSC13
No. of Credits
04
Contact hours
52 Hours
Duration of SEA/Exam
2 hours
40
Summative Assessment
Marks
60
Course Outcomes (COs): After the successful completion of the course, the student will be
able to: CO1. Understand the fundamental concepts of algorithms and their complexity,
including time and space complexity, worst-case and average-case analysis, and Big-O
notation. BL (L1, L2)
CO2. Design algorithms for solving various types of problems, such as Sorting, Searching,
Graph
traversal, Decrease-and-Conquer, Divide-and-Conquer and Greedy Techniques. BL (L1, L2, L3)
CO3. Analyze and compare the time and space complexity of algorithms with other
algorithmic techniques. BL (L1, L2,L3,L4)
CO4. Evaluate the performance of Sorting, Searching, Graph traversal, Decrease-and- Conquer,
Divide-and-Conquer and Greedy Techniques using empirical testing and benchmarking, and
identify their limitations and potential improvements. BL (L1, L2, L3, L4)
CO5. Apply various algorithm design to real-world problems and evaluate their effectiveness and
efficiency in solving them. BL (L1, L2, L3)
Note: Blooms Level(BL): L1=Remember, L2=Understand, L3=Apply, L4=Analyze, L5=
Evaluate, L6= Create
Contents
52 Hrs
Introduction: What is an Algorithm? Fundamentals of Algorithmic problem solving,
Fundamentals of the Analysis of Algorithm Efficiency, Analysis Framework, Measuring the
input size, Units for measuring Running time, Orders of Growth, Worst-case, Best-
case and Average-case efficiencies.
10
Asymptotic Notations and Basic Efficiency classes, Informal Introduction, O-notation,
Ω-notation, θ-notation, mathematical analysis of non-recursive algorithms, mathematical
analysis of recursive algorithms.
10
Brute Force & Exhaustive Search: Introduction to Brute Force approach, Selection
Sort and Bubble Sort, Sequential search, Exhaustive Search- Travelling Salesman
Problem and Knapsack Problem, Depth First Search, Breadth First Search
11
Decrease-and-Conquer: Introduction, Insertion Sort, Topological Sorting
Divide-and-Conquer: Introduction, Merge Sort, Quick Sort, Binary Search, Binary Tree
traversals and related properties.
11
Greedy Technique: Introduction, Prim’s Algorithm, Kruskal’s Algorithm, Dijkstra’s
Algorithm, Lower-Bound Arguments, Decision Trees, P Problems, NP Problems, NP-
Complete Problems, Challenges of Numerical Algorithms.
10
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e
pf2f
pf30
pf31
pf32
pf33
pf34
pf35
pf36
pf37
pf38
pf39
pf3a
pf3b
pf3c
pf3d
pf3e
pf3f
pf40
pf41

Partial preview of the text

Download Fundamentals of Algorithm Analysis: Efficiency, Asymptotic Notations, and Problem Solving and more Study notes Design and Analysis of Algorithms in PDF only on Docsity!

Program

Name

BCA Semester V

Course Title Design and Analysis of Algorithm (Theory)

Course Code: DSC

No. of Credits 04

Contact hours 52 Hours Duration of SEA/Exam 2 hours

Formative Assessment

Marks

40

Summative Assessment

Marks

60

Course Outcomes (COs): After the successful completion of the course, the student will be

able to: CO1. Understand the fundamental concepts of algorithms and their complexity,

including time and space complexity, worst-case and average-case analysis, and Big-O

notation. BL (L1, L2)

CO2. Design algorithms for solving various types of problems, such as Sorting, Searching,

Graph

traversal, Decrease-and-Conquer, Divide-and-Conquer and Greedy Techniques. BL (L1, L2, L3)

CO3. Analyze and compare the time and space complexity of algorithms with other

algorithmic techniques. BL (L1, L2,L3,L4)

CO4. Evaluate the performance of Sorting, Searching, Graph traversal, Decrease-and- Conquer,

Divide-and-Conquer and Greedy Techniques using empirical testing and benchmarking, and

identify their limitations and potential improvements. BL (L1, L2, L3, L4)

CO5. Apply various algorithm design to real-world problems and evaluate their effectiveness and

efficiency in solving them. BL (L1, L2, L3)

Note: Blooms Level(BL): L1=Remember, L2=Understand, L3=Apply, L4=Analyze, L5=

Evaluate, L6= Create

Contents 52 Hrs

Introduction: What is an Algorithm? Fundamentals of Algorithmic problem solving,

Fundamentals of the Analysis of Algorithm Efficiency, Analysis Framework, Measuring the

input size, Units for measuring Running time, Orders of Growth, Worst-case, Best-

case and Average-case efficiencies.

10

Asymptotic Notations and Basic Efficiency classes, Informal Introduction, O-notation,

Ω-notation, θ-notation, mathematical analysis of non-recursive algorithms, mathematical

analysis of recursive algorithms.

10

Brute Force & Exhaustive Search: Introduction to Brute Force approach, Selection

Sort and Bubble Sort, Sequential search, Exhaustive Search- Travelling Salesman

Problem and Knapsack Problem, Depth First Search, Breadth First Search

11

Decrease-and-Conquer: Introduction, Insertion Sort, Topological Sorting

Divide-and-Conquer: Introduction, Merge Sort, Quick Sort, Binary Search, Binary Tree

traversals and related properties.

11

Greedy Technique: Introduction, Prim’s Algorithm, Kruskal’s Algorithm, Dijkstra’s

Algorithm, Lower-Bound Arguments, Decision Trees, P Problems, NP Problems, NP-

Complete Problems, Challenges of Numerical Algorithms.

10

Introduction: What is an Algorithm? Fundamentals of Algorithmic problem solving,

Fundamentals of the Analysis of Algorithm Efficiency, Analysis Framework, Measuring

the input size, Units for measuring Running time, Orders of Growth, Worst-case, Best

case and Average-case efficiencies.

UNIT – 1

INTRODUCTION

What is an algorithm?

Definition: An algorithm is defined as finite sequence of unambiguous instructions followed to

accomplish a given task. It is also defined as unambiguous, step by step procedure (instructions)

to solve a given problem in finite number of steps by accepting a set of inputs and producing the

desired output. After producing the result, the algorithm should terminate. The notion of an

algorithm is pictorially represented as shown below:

Input

ProblemAlgorithmProgramComputerOutput

Observe the following activities to see how an algorithm is used to produce the desired

result:

 The solution to a given problem is expressed in the form of an algorithm.

 The algorithm is converted into a program.

 The program when it is executed, accept the input and produces the desired output

The properties of an algorithm?” An algorithm must satisfy the

  • Input: Each algorithm should have zero or more inputs. The range of inputs for which

algorithm works should be satisfied

  • Output: The algorithm should produce correct results. At least one output has to be

produced.

  • Definiteness: Each instruction should be clear and unambiguous.
  • Effectiveness : The instructions should be simple and should transform the given input to

the desired output.

  • Finiteness: The algorithm must terminate after a finite sequence of instructions.

Note: By looking at the algorithm, the programmer can write the program in C or C++ or any of

the programming language. Before writing any program, the solution has to be expressed in the

form of algorithms.

Program vs. Algorithm

The difference between program and algorithm are as follows

Fundamentals of Algorithmic

Program Algorithm

Program is an implemented coding of a

solution to a problem based on the

Algorithm.

An algorithm is a step by step outline or

flowchart how to solve a problem.

The implementation phase produces a program. The design phase produces an algorithm.

Program does not have to satisfy the

finiteness condition.

Algorithms have to satisfy the finiteness

condition.

Algorithm design and analysis process

A sequence of steps involved in designing and analyzing an algorithm is shown inthe figure

below. :

 Understand the problem

 Decide on Computational Device Exact Vs Approximate Algorithms

 Algorithm Design Techniques

 Design an algorithms

 Prove Correctness

 Analyze the Algorithm

 Code the Algorithm

Understanding the Problem:

Begin by clearly understanding the problem you are trying to solve. Identify the input,

output, and constraints. This step is crucial for defining the scope of the algorithm.

Deciding on Computational Device:

Consider the computational device or model on which the algorithm will run. Different

devices may have different resource constraints, and the algorithm should be designed to

work efficiently within those constraints.

Exact Vs. Approximate Algorithms:

Decide whether an exact solution is necessary or if an approximate solution would suffice.

Exact algorithms guarantee optimal solutions, while approximate algorithms provide

solutions that are close to optimal but might be obtained faster.

Algorithm Design Techniques:

Choose appropriate algorithm design techniques based on the problem at hand. Common

techniques include:

Divide and Conquer : Break the problem into smaller sub problems and solve them

independently.

Dynamic Programming: Solve sub problems and store their solutions to avoid

redundant computations.

Greedy Algorithms: Make locally optimal choices at each step with the hope of

finding a global optimum.

Design an Algorithm:

Develop the step-by-step procedure to solve the problem based on the chosen design technique.

Clearly define the algorithm's input, output, and the sequence of operations to achieve the

desired result.

Prove Correctness :

Provide a mathematical or logical proof that the algorithm produces the correct output for any

valid input. This step ensures the algorithm reliably solves the problem it was designed for.

Analyze the Algorithm:

Assess the algorithm's efficiency, primarily in terms of time and space complexity. Perform a

worst-case, best-case, and average-case analysis to understand how the algorithm performs

under different scenarios.

Code the Algorithm:

Implement the algorithm in a programming language of choice. Pay attention to details, and

ensure that the code accurately reflects the designed algorithm. Test the algorithm with

various inputs to validate its correctness and efficiency.

b[j]  a[i] ; j j + 1

En

d if End

for

Step 4: [Output the prime numbers between 2 to

n] for i0 to j– 1

W

rite b[i]

End for

Step 5: [Finished]

Exit

Units for measuring Running time

The running time of algorithms is often measured using different units depending on the

context and the granularity of analysis. Here are common units for measuring running time:

Seconds (s):

 The most straightforward unit, representing the actual time in seconds that an

algorithm takes to run on a specific machine.

 Suitable for measuring real-world performance but can be influenced by external

factors like the machine's load.

Milliseconds (ms):

 A smaller unit than seconds, measuring time in thousandths of a second.

 Useful for more precise measurement when algorithms have relatively fast execution

times.

Microseconds (μs):

 An even smaller unit than milliseconds, measuring time in millionths of a second.

 Appropriate for very fast algorithms or when extremely precise timing is required.

Nanoseconds (ns):

 A unit smaller than microseconds, measuring time in billionths of a second.

 Common in the context of measuring operations at the hardware level or very low-

level algorithmic optimizations.

Operations or Basic Steps :

 Instead of measuring time, algorithms can be analyzed based on the number of basic

steps or operations they perform.

 This unit provides an abstract measure of algorithmic complexity, independent of the

specific hardware or software environment.

Big O Notation (O()):

 Represents the upper bound of an algorithm's time complexity in terms of a

mathematical function, typically based on the input size.

 Provides a theoretical measure of efficiency, ignoring constant factors and lower-

order terms.

Instruction Count:

 The number of machine instructions executed by an algorithm.

 Useful for low-level analysis and optimization, considering the specific machine

architecture.

Comparisons or Swaps:

 For sorting algorithms, measuring the number of element comparisons or swaps

provides insight into their efficiency.

 Relevant for algorithms where the primary operations involve comparisons or data

rearrangement.

Analysis of algorithms

The main purpose of algorithm analysis is to design most efficient algorithms. Let use “On

what factors efficiency of algorithm depends?” The efficiency of an algorithm depends on

two factors:

1. Space efficiency

2. Time efficiency

“ What is space efficiency?”

Definition: The space efficiency of an algorithm is the amount of memory required to run

the program completely and efficiently. If the efficiency is measured with respect to the

space (memory required), the word space complexity is often used. The space complexity of

an algorithm depends on following factors:

Components that affect space

1. Program space

2. Data space

3. Stack space

  • Program space: The space required for storing the machine program generated

by the compiler or assembler is called program space.

  • Data space : The space required to store the constants, variables etc., is called data
  • Stack space: The space required to store the return address along with parameters

that are passed to the function, local variables etc., is called stack space.

Note: The new technological innovations have improved the computer’s speed and memory

size by many orders of magnitude. Now a days, space requirement for an algorithm is not a

concern and hence, we are not concentrating on space efficiency. Let us concentrate only on

time efficiency.

Definition: We expect the algorithms to work faster for all values of n. Some algorithms

execute faster for smaller values of n. But, as the value of n increases, they tend to be very

slow. So, the behavior of some algorithm changes with increase in value of n. This change in

behavior of the algorithm and algorithm's efficiency can be analyzed by considering the

highest order of n. The order of growth is normally determined for larger values of n for the

following reasons:

 The behavior of algorithm changes as the value of n increases

 In real time applications we normally encounter large values of n

For example, the order of growth with respect to two running times is shown below:

 Suppose T(n) approx c* C(n). Observe that T(n) varies linearly with increase

or decrease in the value of n. In this case, the order of growth is linear.

 Suppose T(n) approx c* C(n ^ 2). In this context, the order of growth is quadratic.

Note: If the order of growth of one algorithm is linear and the order of growth of second

algorithm to solve the same problem is quadratic, then it clearly indicates that running time

of first algorithm is less and it is more efficient. So, while analyzing the time efficiency of an

algorithm, the order of growth of n is important. Let us discuss orders of growth in the next

section.

The concept of order of growth can be clearly understood by considering the common

computing time functions shown in table 1.1.

Note: By comparing N (which is linear) and 2"(which is exponential) it is observed from the

above table that exponential function grows very fast even for small variation of N. So, an

algorithm with linear running time is preferred over an algorithm with exponential running

time. The basic efficiency of asymptotic classes are shown below:

1 or any constant: Indicates that running time of a program is constant.

log N : Indicates that running time of a program is logarithmic. This running time occurs in

programs that solve larger problems by reducing the problem size by a constant factor at

each iteration of the loop (For example, binary search).

N: Indicates that running time of a program is linear. So, when N is 1000, the running time is

1000 units. When N is doubled, so does the running time. (For example linear search)

N log N: Indicates that running time of a program is N log N (For lack adjective, it is used as

it is instead of linear, quadratic etc.). The algorithm elements in ascending order such as

quick sort, merge sort and heap sort wave this running time. (These sorting techniques are

discussed in later chapters)

N

2

: Indicates that running time of a program is quadratic. The algorithms normally will have

two loops. For example, sorting algorithms such as bubble sort, selection sort, addition and

subtraction of two matrices have this running time.

N

3

: Indicates that running time of a program is cubic. The algorithms with running time will

have three loops. For example, matrix multiplication, algorithm to solve simultaneous

equations using gauss-elimination method will have this running time.

N

: Indicates that running time of an algorithm is exponential. The tower of Hanoi problem

and algorithms that generate subsets of a given set will have this running time

N! : Indicates that running time of an algorithm is factorial. The along generate all

permutations of set will have this running time.

Note: All the above functions can be ordered according to their order of growth (from lowest

to highest) as shown below:

1 < log(n) < n < n * log(n) < n

2

< n

3

n

< n!

Note: Even though running times of 2

N

and N! are different, normally both classes are

considered as exponential. The algorithms with this running time can be solved practically

for smaller values of n.

Note: For a very large value of n, the exponential function 2" and factorial function n!

Generate a very high value such that even the fastest computer can take years to execute an

algorithm.

For example, a computer which executes 10

12

instructions per second takes 4*

10

years to

execute 2

100

operations. The factorial function n! is much more than the value specified for

n

a) n(n-1) and 2000n²

n²+1 2000n²

order- 2 order- 2

Worst-case, Best-case and average case efficiencies

Now the question is "Will the algorithm efficiency depends on the size of algorithm's input

alone?" For some of the problems, the time complexity will not depend on the number of

inputs alone. For example, while searching for a specific item in an array of n elements using

linear search, we have following three situations:

 An item we are searching for may be present in the very first location itself. In this case

only one item is compared and this is the best case.

 The item may be present somewhere in the middle which definitely takes some time.

Running time is more when compared to the previous case for the same value of n. Since we

do not know where the item is we have to consider the average number of cases and hence

this situation is an average case.

 The item we are searching for may not be present in the array requiring n number of

comparisons and running time is more than the previous two cases. This may be considered

as the worst case.

So, knowing n alone itself is not enough to estimate the run time of an algorithm or a

function. In such cases, we may have to find the worst-case efficiency, best case efficiency

and average case efficiency. Now, let us see "What is worst case efficiency?"

"What is worst case efficiency?"

Definition: The efficiency of an algorithm for the input of size n for which the algorithm

takes longest time to execute among all possible inputs is called worst case efficiency For

example, if we use linear search and the item to be searched is no present in the array, then it

is an example of worst case efficiency.

In the worst case, the algorithm runs for the longest duration among all possible inputs for a

given size. Here, maximum number of steps are executed for that input.

"What is best case efficiency?"

Definition: The efficiency of an algorithm for the input of size n for which the algorithm

takes least time during execution among all possible inputs of that size is called best case

efficiency.

In the best case, the algorithm runs fastest for the input specified. For example, in linear

search, if the item to be searched is present in the beginning, then it is an example of the best

case efficiency.

Note: In the average case efficiency, the average number of basic operations executed will be

considered. This is required only for the randomized input.

Example: Searching for an Element in an Array

Suppose you have an array of numbers, and you want to find a specific element in that array. def

search_element(arr, target):

for num in arr:

if num == target: return True

return False

Now, let's analyze the efficiency of this algorithm in terms of worst-case, best-case, and

average-case scenarios.

Worst-case efficiency:

 This is the scenario where the algorithm takes the maximum amount of time to

complete.

 In our example, the worst-case scenario occurs when the target element is at the end of

the array or is not present in the array.

 The worst-case time complexity is O(n), where n is the number of elements in the

Worst-case scenario arr [1, 2, 3, 4, 5]

target = 5

result = search_element(arr, target)

In this case, the algorithm has to go through the entire array to find the target element.

Best-case efficiency:

 This is the scenario where the algorithm takes the minimum amount of time to

complete.

 In our example, the best-case scenario occurs when the target element is at the

beginning of the array.

 The best-case time complexity is O(1), as the algorithm may find the target element in

the first iteration.

Best-case scenario arr = [1, 2, 3, 4, 5]

target = 1

result = search_element(arr, target)

In this case, the algorithm finds the target element in the first iteration.

Average-case efficiency:

 This is the scenario where the algorithm takes an average amount of time to complete,

considering all possible inputs.

 The average-case time complexity is often more challenging to analyze and may

Ex 1: Let g(n) =n. Since n and I have smaller order of growth and n’ has same order of growth when

compared to n², we say.

Formal Definitions of Asymptotic

notations O (Big-Oh)

Now, let us see “What is Big Oh (0) notation?”

Definition: Let f(n) be the time efficiency of an algorithm. The function f(n) is said to be O(g(n))

[read as big-oh of g(n)), denoted by

f(n) = O(g(n)) or

f(n) = O(g(n))

If and only if there exists a positive constant c and positive integer n 0

satisfying the constraint

f(n) <=c*g(n) for all n≥ n 0

So, if we draw the graph f(n) and c*g(n) verses n, the graph of the function f(n) lies

Below the graph of c g(n) for sufficiently large value of n as shown below:

Here, c .g(n) is the upper bound. The upper bound on f(n) indicates that function f(n) will not

consume more than the specified time c* g(n) i.e., running time of function f(n) maybe equal to c

.g(n), but it will never be worse than the upper bound. So, we can say that f(n) is generally faster

than g(n)

Note: Big-O is the formal method of expressing the upper bound of an algorithm’s running

time. It is a measure of the longest amount of time it could possibly take for the Algorithm to

complete.

Note: The function g(n) is normally expressed using higher order terms of f(n) This is achieved

using the following steps:

 Take the lower order term of f(n) replace the constant with next higher order

variable. Repeat this step, till we get the higher order term and call it as c .g(n)

 Once the constraint “ f(n) <= c.g(n) for n >= n

0

is obtained we say f(n) ∈ O(g(n))

Example : Let f(n) = 100n + 5 Express f(n) using big-oh

Solution: It is given that f(n) = 100n + 5 Replacing 5 with n (so that next higher order term is

obtained), we get 100n + n and call it c.g(n)

i.e..c. g(n) = 100n + n for n = 5

= 101nforn =5;

Now, the following constrain is satisfied:

f(n) <=c * g(n) for n ≥ n 0

I .e.,100n+5<=101 nfor n >= 5

It is clear from the above relations that c = 101 g(n) = n and n 0

=5. So , by definition

f(n) ∈ O(g(n)) * I .e.., f(n) ∈ O(n)

Ω(Big-Omega)

Definition: Let f(n) be the time complexity of an algorithm. The function f(n) is said tobe

Ω(g(n)) [read as big-omega of g(n)] which is denoted by

f(n) = Ωg((n)) or

f(n) or = Ω(a(n))

If and only if there exists a positive constant c and non-negative integer no satisfying the

constraint f(n)>=c*g(n) for all n≥ n 0

So, if we draw the graph f(n) and c*g(n) verses n, the graph of f(n) lies above the graph of g(n)

for sufficiently large value of n as shown below:

Big-Theta

Definition: Let f(n) be the time complexity of an algorithm. The function f(n) is said to be big-

theta of g(n), denoted

f(n) = Θ(g(n)) or f(n)= Θ(g(n))

if and only if there exists some positive constants c 1

, c 2

and non-negative integer n o

satisfying

the constraint

c 1*

g(n)<=f(n)<=c 2

  • g(n) for all n≥ n 0

So, if we draw the graph f(n), c 1

,g(n) and c₂ g(n) verses n, the graph of function f(n) lies

above the graph of c 1

*g(n) and lies below the graph of c 2

  • g(n) for sufficiently large value of n

as shown below:

This notation is used to denote both lower bound and upper bound on a function f(n) within a

constant factor. The upper bound on f(n) indicates that function f(n) will not consume more than

the specified time cog(n).The lower bound on f(n) indicates that function f(n) in the best case will

consume at least the specified time c₁*g(n).