Lecture 2 DSA
Lecture 2 DSA
Lecture 2 DSA
CS-201
Lecture # 02
Definition of Algorithm
• Properties of algorithms:
• Input from a specified set,
• Output from a specified set (solution),
• Definiteness (assuredness) of every step in the
computation,
• Correctness of output for every possible input,
• Finiteness of the number of calculation steps,
• Effectiveness of each calculation step and
• Generality for a class of problems.
4
A question?
• Suppose computers were infinitely fast and
computer memory are free (no issue in cost)
• Yes
In reality
7
8
Complexity
• Comparison: time complexity of algorithms A and B
n 5,000n 1.1n
10 50,000 3
9
Complexity
10
Asymptotic Efficiency Algorithm
• When the input size is large enough so that the rate of
growth/order of growth of the running time is relevant.
11
Asymptotic Notation
12
Asymptotic Notation
13
Asymptotic Notation
• O – Big O
• The notation Ο(n) is the formal way to express the upper
bound of an algorithm's running time. It measures the
worst-case time complexity or the longest amount of
time an algorithm can possibly take to complete.
• - Theta (θ)
• The notation θ(n) is the formal way to express both the
lower bound and the upper bound of an algorithm's
running time.
• – Omega
• The notation Ω(n) is the formal way to express the lower
bound of an algorithm's running time. It measures the
best-case time complexity or the best amount of time an
algorithm can possibly take to complete.
14
Example: Find sum of array elements
Algorithm arraySum (A, n)
Input array A of n integers
Output Sum of elements of A # operations
sum 0 1
for i 0 to n − 1 do n+1
sum sum + A [i] n
return sum 1
17
O-Notation
18
Example
• O(g(n)) = {f(n) : there exist positive constants c
and n0 such that 0 f(n) c g(n) for all n n0 }
• f(n) = 5n+2
• 0 5n+2 6n
• n=0 → 020 (no) So n0=2, c=6, g(n)=n
• n=1 → 076 (no) f(n)= O(g(n))
• n=2 → 01212 (yes)
• n=3 → 01718 (yes)
19
Big-O Notation
(Examples)
1. f(n)=n/2 –3
0 n/2 –3 n/2; n0=6; c=1/2; f(n)=O(n)
2. f(n) = n2-n
0 n2–n n2; n0=0; c=1; f(n)=O(n2)
20
- Notation
• For a given function g(n)
• (g(n)) = {f(n) : there exist positive constants c
and n0 such that 0 c g(n) f(n) for all n n0}
21
- Notation
22
Example
• (g(n)) = {f(n) : there exist positive constants c
and n0 such that 0 c g(n) f(n) for all n n0}
• f(n) = 5n+2
• 0 5n 5n+2
• n=0 → 002 (yes) So n0=0, c=5, g(n)=n
• n=1 → 057 (yes) f(n)= (g(n))
• n=2 → 01012 (yes)
23
- Notation (Big Theta)
24
- Notation
g(n) is an asymptotically
tight bound for f(n).
Example
5n+2 = (n)
Determine the positive constant n0, c1, and c2 such
that the above conditions satisfies
5n 5n+2 6n
26
Example Contd ...
• That is
(g(n)) = O(g(n)) (g(n))
28
Relations Between , O,
29
The Growth of Functions
• “Popular” functions g(n) are
n.log n, 1, 2n, n2, n!, n, n3, log n
30
Comparing Growth Rates
2n n3
n2 n log2 n
T(n)
log2 n
Problem Size