ADA Unit I
ADA Unit I
Dr. J. GHAYATHRI
Associate Professor
Algorithms and Computing
It is a set of steps or
procedures that lead to a
desired outcome or output
Algorithm
An algorithm is a sequence
of unambiguous instructions
for solving a problem, i.e.,
for obtaining a required
output for any legitimate
input in a finite amount of
time.
Computers and algorithms
needed.
1. Understanding the Problem[Cont..]
An input to an algorithm specifies an instance of the problem the
algorithm solves.
It is very important to specify exactly the set of instances the
algorithm needs to handle.
If you fail to do this, your algorithm may work correctly for a
majority of inputs but crash on some “boundary” value.
A correct algorithm is not one that works most of the time, but one
that works correctly for all legitimate inputs.
Do not skimp on this first step of the algorithmic problem-solving
process; otherwise, you will run the risk of unnecessary rework
2. Ascertaining the Capabilities of the Computational Device
Sequential algorithms :
Algorithms in use today are still meant to be programmed for a computer
closely resembling the von Neumann machine
The essence of this architecture is used by random-access machine (RAM).
In this, instructions are executed one after another, one operation at a time.
Algorithms designed to be executed on this RAM are called sequential
algorithms.
Parallel Algorithms:
Some newer computers that can execute operations concurrently, i.e., in
parallel. Algorithms using this capability are called parallel algorithms.
Still, studying the classic techniques for design and analysis of algorithms under the RAM model remains the
cornerstone of algorithmics for the foreseeable future
3. Choosing between Exact and Approximate Problem Solving
Exact algorithm
Solving the problem exactly
Approximation algorithm
Solving problem approximately.
Why?
1. cannot be solved exactly for most of their instances
Example: Extracting square roots, solving nonlinear equations, and
evaluating definite integrals.
2. Available algorithms for solving a problem exactly can be
unacceptably slow because of the problem’s intrinsic complexity
4. Algorithm Design Techniques
Pseudocode
A mixture of a natural language and programming languagelike
constructs.
Its usage often yields more crisp algorithm descriptions.
7. Proving an Algorithm’s Correctness
Sorting
Searching
String processing
Graph problems
Combinatorial problems
Geometric problems
Numerical problems
SORTING
It deals with finding a given value, called a search key, in a given set
Straightforward sequential search to a spectacularly efficient but
limited binary search and algorithms based on representing the
underlying set in a different form more conducive to searching.
No single algorithm that fits all situations best
Searching has to be considered with two other operations:
An addition to and deletion from the data set of an item.
Choose balanced data structures and algorithms
Organizing very large data sets for efficient searching poses special
challenges with important implications for real-world applications
STRING PROCESSING
Problem
string matching.
Graph Problem
Collection of points called vertices, some of which are connected by line
segments called edges
Transportation, communication, social and economic networks, project
scheduling, and games.
Basic graph algorithms include
Graph-traversal algorithms (how to reach all the points in a network?),
Shortest-path algorithms (what is the best route between two cities?),
Topological sorting for graphs with directed edges (is a set of courses
with their prerequisites consistent or self-contradictory?).
Graph Problem[Cont..]
Some graph problems are computationally very hard; the most well-known
examples are the traveling salesman problem and the graph-coloring
problem.
The traveling salesman problem (TSP)is the problem of finding the
shortest tour through n cities that visits every city exactly once.
In addition to obvious applications involving route planning, it arises in
such modern applications as circuit board and VLSI chip fabrication, X-
ray crystallography, and genetic engineering.
The graph-coloring problem the vertices of a graph so that no two adjacent
vertices are the same color : a solution to the graph-coloring problem
yields an optimal schedule.
Combinatorial Problems
To find a combinatorial object—such as a Permutation, a combination
When the order doesn't matter, it is a Combination
When the order does matter it is a Permutation
or a subset—that satisfies certain constraints.
A desired combinatorial object may also be required to have some
additional property such as a maximum value or a minimum cost.
Combinatorial problems are the most difficult problems in computing
First, the number of combinatorial objects typically grows extremely fast
with a problem’s size, reaching unimaginable magnitudes even for
moderate-sized instances.
Second, there are no known algorithms for solving most such problems
exactly in an acceptable amount of time
Geometric Problems
Deals with geometric objects such as points, lines, and polygons.
The ancient Greeks were very much interested in developing procedures
for solving a variety of geometric problems, including problems of
constructing simple geometric shapes—triangles, circles, and so on—
with an unmarked ruler and a compass.
Today people are interested in geometric algorithms with quite different
applications in mind, such as computer graphics, robotics, and
Tomography (x-ray technique)
Classic problems of computational geometry:
(i) Closest-pair problem (ii) convex-hull problem.
(i) Closest-pair problem : Given n points in the plane, find the closest pair
among them.
(ii) Convex-hull problem : Finds the smallest convex polygon that would
include all the points of a given set.
Numerical Problems
• Correctness
• Lower bounds
• Optimality
Analysis of algorithms
• Issues:
– correctness
– Time efficiency
– Space efficiency
– Optimality
• Approaches:
– Theoretical analysis
– Empirical analysis
Theoretical analysis of time efficiency (Measuring Running Time)
Basic operation: the operation that contributes most towards the running time
of the algorithm Cop - Execution Time of the
input size Algorithm
Visiting a vertex or
Typical graph problem #vertices and/or edges
traversing an edge
Assume
Double the size of input
Orders of growth
• Example:
– How much faster will algorithm run on computer that is twice as fast?
– How much longer does it take to solve problem of double input size?
Orders of Growth (Constant Multiples for large-size inputs)
Values of some important functions as n
Empirical analysis of time efficiency
Standard assumptions
(a) the probability of a successful search is equal to p (0 ≤ p ≤ 1)
(b) the probability of the first match occurring in the ith position of the list
is the same for every i.
We can find the average number of key comparisons Cavg(n) as follows.
● Case (a) Successful search, the probability of the first match occurring in the
ith position of the list is p/n for every i, and the number of comparisons made
by the algorithm in such a situation is obviously i.
● Case (b) Unsuccessful search, the number of comparisons will be n with the
probability of such a search being (1 − p). Therefore
Average-Case Efficiency
If p=1
Asymptotic Notations and Basic Efficiency Classes
(Big Oh) - Ο
(Big Omega) - Ω
(Big Theta) Θ
t (n) and
g(n) can be any nonnegative functions defined on the set of
natural numbers
t(n) -- An algorithm’s running time
g(n) -- Some simple function to compare the count with.
NUMBER SYSTEM
Natural Numbers: Range from 1 to infinity. Positive Numbers / Counting Numbers. Represented
by the symbol N.
Integers: Collection of Whole Numbers plus the negative values of the Natural Numbers. From
the Infinity at the Negative end and Infinity at the Positive end, including zero. Integers are
Fractions: Written in the form of x/y, where, x belongs to Whole numbers and y belongs to
Rational Numbers: Represented in the fraction form i.e. x/y. Here, x and y both are integers and y≠0. All the
fractions are rational numbers but not all the rational numbers are fractions.
Irrational Numbers: Irrational numbers are the numbers that can’t be represented in the form of fractions i.e.
they can not be written as x/y.
Real and Imaginary Numbers: Numbers represented in the decimal form. These numbers include whole
numbers, integers, fractions, etc. All the integers belong to Real numbers but all the real numbers do not belong to
the integers.
Imaginary Numbers are all those numbers that are not real numbers. These numbers when squared will result in a
negative number. The √-1 is represented as i. These numbers are also called complex numbers.
Prime Numbers and Composite Numbers: Numbers that do not have any factors other than 1 and the
number itself are termed as Prime Numbers. All the numbers other than Prime Numbers are termed as Composite
Numbers except 0. Zero is neither prime nor a composite number.
For example,
But
Θ(g(n))
Θ(g(n)) is the set of all functions that have the same order
of growth as g(n)
Infinitely in,
𝑛2 + sin n
𝑛2 + log n.
O – notation (FORMAL)
Definition:
f(n) O(f(n))
Examples:
• 10n vs. n2
• n(n+1)/2 vs. n2
L’Hôpital’s rule and Stirling’s formula
L’Hôpital’s rule:
If limn f(n) = limn g(n) = and the derivatives f´, g´ exist, then
Stirling’s formula
Example: 2n vs. n!
Properties of Limits
limx→a c = c, where c is a constant quantity.
Value of limx→a bx + c = ba + c
Since the limit is equal to a positive constant, the functions have the same order
of growth or, symbolically,
Orders of growth of some important functions
• order log n < order n (>0) < order an < order n! < order nn
Basic Efficiency classes
Class Name Comments
1 Constant Short of Best-case
• Set up a sum for the number of times the basic operation is executed
liu1 = 1+1+…+1 = u - l + 1
In particular, liu1 = n - 1 + 1 = n (n)
• So, no need to distinguish among the worst, average, and best cases here
• C(n) the number of times comparison is executed
• The algorithm makes one comparison on each execution of the loop, &
repeated for each value of the loop’s variable i within 1 and n − 1inclusive.
R1
R2
Two summation formulas
Element uniqueness problem
check whether all the elements in a given array of n elements are distinct.
• The natural measure of the input’s size = n, (number of elements in the
array).
(ii) arrays in which the last two elements are the only pair of equal
elements.
• For such inputs, one comparison is made for each repetition of the
innermost loop, i.e., for each value of the loop variable j between
• This is repeated for each value of the outer loop, i.e., for each value of the
loop variable i between its limits 0 and n − 2.
Compute the sum faster using
On each repetition of the innermost loop each of the two is executed exactly
once.
sum for the total number of multiplications M(n) executed by the algorithm.
• Compute this sum by using formula (S1) and rule (R1) given above.
Starting with the innermost sum which is equal to n, we get
• Running time of the algorithm on a particular machine
• More accurate estimate by taking into account of the time spent on the
additions too where ca is the time of one addition
Example 4: Counting binary digits
• Number of times the comparison executed is larger than the number of repetitions
of the loop’s body by exactly 1, the choice is not that important.
• The loop variable takes on only a few values between its lower and upper limits;
• So use an alternative way of computing the number of times the loop is executed.
• We could also get this answer by applying the analysis technique based on
recurrence relations; we discuss this technique in the next section because it is
more pertinent to the analysis of recursive algorithms
General Plan for Analysis of Recursive Algorithms
• Check whether the number of times the basic op. is executed may vary on
different inputs of the same size.
(If it may, the worst, average, and best cases must be investigated
separately)
• Solve the recurrence (or, at the very least, establish its solution’s order of
growth) by backward substitutions or another method.
Example 1: Recursive evaluation of n!
F(0) = 1
Size:
Basic operation:
Recurrence relation:
• For simplicity, consider n as input size
• Find an initial condition : The value with which the sequence starts.
• Obtain this value by inspecting the condition that makes the algorithm stop
its recursive calls:
if n = 0 return 1.
(i) Calls stop when n = 0, the smallest value of n for the execution of
the algorithm and M(n) is 0.
Initial condition
Setting up the recurrence relation and initial condition for the algorithm’s
number of multiplications M(n):
Two Recursive functions used are
(i) Factorial function F(n) itself;
F(n) = F(n − 1).n for every n > 0, F (0) = 1.
(ii)The number of multiplications
M(n) needed to compute F(n) by the recursive algorithm
• Initial : n disks of different sizes that can slide onto any of three pegs.
• Initially, all the disks are on the first peg in order of size, the largest on the
bottom and the smallest on top.
• Goal : To move all the disks to the third peg, using the second one as an
auxiliary, if necessary.
1) Move n > 1 disks from peg 1 to peg 3 - peg 2 auxiliary
5) if n = 1, move the single disk directly from the source peg to the destination
peg.
The Tower of Hanoi Puzzle
• With the obvious initial condition M(1) = 1, the recurrence relation for the
number of moves M(n):
• When a recursive algorithm makes more than a single call to itself, it can
be useful for analysis purposes to construct a tree of its recursive calls.
• In this tree, nodes correspond to recursive calls, and we can label them
with the value of the parameter of the calls.
• By counting the number of nodes in the tree, we can get the total number of
calls made by the Tower of Hanoi algorithm
Tree of calls for the Tower of Hanoi Puzzle
Counting #bits
• Set up a recurrence and an initial condition for the number of additions
A(n) made by the algorithm.
• Since the recursive calls end when n is equal to 1 and there are no
additions made then, the initial condition is A(1) = 0.
• The presence of [n/2] in the function’s argument makes the method of
backward substitutions stumble on values of n that are not powers of 2.
• So let us apply this recipe to our recurrence, which for n = 2𝑘 takes the form
Now backward substitutions encounter no problems: