Design and Analysis of Algorithms: Muhammad Nasir
Design and Analysis of Algorithms: Muhammad Nasir
Algorithms
Lecture # 4
Muhammad Nasir
Department of Computer Science
COMSATS University Islamabad,
Lahore Campus
[email protected]
Running Time Analysis (Revisited)
• Depends upon the input size e.g. n
• Depends upon the structure of input
Complexity with input size
Asymptotic Notation
Goal: to simplify analysis by getting rid of
unneeded information (like “rounding”
1,000,001≈1,000,000)
We want to say in a formal way 3n2 ≈ n2
Asymptotic Notation
Categorize algorithms based on asymptotic growth
rate e.g. linear, quadratic, polynomial, exponential.
Ignore small constant and small inputs.
Estimate upper bound and lower bound on growth
rate of time complexity function.
Describe running time of algorithm as n grows to
infinity.
Limitations:
Not always useful for analysis on fixed-size inputs.
All results are for sufficiently large inputs.
Asymptotic Notation
Concentrate on order of growth of an
algorithm’s basic operation as the input
size grows.
Asymptotic Notations O, Ω, Θ, o, 𝜔.
Θ-notation to mean “order exactly”.
O-notation to mean “order at most”.
Ω-notation to mean “order at least”.
Little o to mean “tight upper bound”.
Little 𝜔 to mean “tight lower bound”.
Classes of Functions
Let {g(n)} denote the class (set) of functions that are
O(g(n))
We have
{n} {n2} {n3} {n4} {n5} …
where the containment is strict
{n3}
{n2}
{n}
Asymptotic analysis - terminology
Special classes of algorithms:
• Logarithmic: O(log n)
• Linear: O(n)
• Quadratic: O(n2)
• Polynomial: O(nk), k ≥ 1
• Exponential: O(an), n > 1
Polynomial vs. exponential ?
Logarithmic vs. polynomial ?
Asymptotic Running Times
Here is a list of common asymptotic running times:
Θ(1): Constant time; can’t beat it!
Θ(logn): Binary Search (Sorted array of length n).
Θ(n): About the fastest that an algorithm can run.
Θ(nlogn): Best sorting algorithms.
Θ(𝑛2 ), Θ(𝑛3 ): Polynomial time. Acceptable when n is not to
large (𝑛 ≤ 1000).
Θ(2𝑛 ), Θ(3𝑛 ): Exponential time. Acceptable only if n is small,
e.g., 𝑛 ≤ 50.
Θ(𝑛!), Θ(𝑛𝑛 ): Acceptable only for really small n, e.g. 𝑛 ≤ 20.
O-notation (Informal Introduction)
O(g(n)) is the set of all functions with a lower or
same order of growth as g(n), within a constant
multiple, as n goes to infinity
n ∈ O(n2) and ½ n(n−1) ∈ O(n2)
n3 ∉ O(n2) and n4+n+1 ∉ O(n2)
O-notation (Formal Introduction)
A function t(n) is said to be of O(g(n)),
denoted t(n)∈O(g(n)), if t(n) is bounded above
by some constant multiple of g(n) for all large
n,
i.e., if there exist some positive constant
c and some non-negative integer n0 such that
t(n) ≤ cg(n) for all n ≥ n0.
O-notation (Formal Introduction)
O-notation (Formal Introduction)
• Let t(n) = 5n + 25
• find the constants c and n0 to prove
formally that t(n) ∈ O(n2)
Ω-notation (Informal Introduction)
𝒇 𝒏 = 𝟖𝒏𝟐 + 𝟐𝒏 − 𝟑