Iterative Algorithms and Their Analysis - Asymptotic Notations
Iterative Algorithms and Their Analysis - Asymptotic Notations
• Asymptotic Notations
– Big O, Notations
1
Example I:
Finding the sum of an array of numbers
int Sum(int A[], int N) { • How many steps does
int sum = 0; this algorithm take to
for (i=0; i < N; i++){
finish?
sum += A[i]; – We define a step to be
} //end-for a unit of work that can
be executed in
return sum; constant amount of
} //end-Sum time in a machine.
2
Example I:
Finding the sum of an array of numbers
Times
Executed
int Sum(int A[], int N) {
int sum = 0; 1
4
Linear Search
return -1; 1
} //end-LinearSearch ---------
Total: 1+3*N+1 = 3N+2
5
Example V: Binary Search
• Problem: You are given a sorted array of
integers, and you are searching for a key
− Linear Search – T(n) = 3n+2 (Worst case)
− Can we do better?
− E.g. Search for 55 in the sorted array below
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
3 8 10 11 20 50 55 60 65 70 72 90 91 94 96 99
6
Example V: Binary Search
• Since the array is sorted, we can reduce our search space
in half by comparing the target key with the key
contained in the middle of the array and continue this way
• Example: Let’s search for 55
0 1 2 3 4 7 8 11 15
3 8 10 11 20 50 55 60 65 70 72 90 91 94 96 99
(left right )
left middle right
2
0 1 2 3 4 6 7 8 11 15
3 8 10 11 20 50 55 60 65 70 72 90 91 94 96 99
7
Binary Search (continued)
0 1 2 3 4 5 6 7 8 11 15
3 8 10 11 20 50 55 60 65 70 72 90 91 94 96 99
0 1 2 3 4 5 6 7 8 11 15
3 8 10 11 20 50 55 60 65 70 72 90 91 94 96 99
lef
t ig ht
Eliminated r
middle
• Now we found 55 Successful search
• Had we searched for 57, we would have terminated at the
next step unsuccessfully
8
Binary Search - Algorithm
// Return the index of the array containing the key or –1 if key not found
int BinarySearch(int A[], int N, int key){
left = 0;
right = N-1;
• 3 asymptotic notations
– Big-O --- Asymptotic upper bound
– Omega --- Asymptotic lower bound
– Theta --- Asymptotic tight bound
10
Big-Oh Notation: Asymptotic Upper Bound
• T(n) = O(f(n)) [T(n) is big-Oh of f(n) or order of f(n)]
– If there are positive constants c & n0 such that
T(n) <= c*f(n) for all n >= n0
c*f(n)
Running Time
T(n)
n0 Input size N
T(n)
Running Time
c*f(n)
n0 Input size N
T(n)
c1*f(n)
n0 Input size N
14
Some Math
N
N ( N 1)
S(N) = 1 + 2 + 3 + 4 + … N =
i 1
i
2
N
N * ( N 1) * (2n 1) N 3
Sum of Squares: i
2
i 1 6 3
N 1
N
A 1
Geometric Series:
i 0
A
i
A 1
A>1
N 1
N
1 A A<1
i 0
A i
1 A
(1)
15
Some More Math
Linear Geometric
( n 1)
n
( n 1) x nx n
x
Series: ix i x 2 x 2 3x 3 ... nx n
i 0 ( x 1)2
n
1 1 1 1
Harmonic Series: H n 1 ... (ln n) O(1)
i 1 i 2 3 n
n n n
• Linearity of Summations: (4i
i 1
2
6i ) 4 i 6 i
i 1
2
i 1
17