Lecture # 20 - New
Lecture # 20 - New
Lecture No 7
Lecture No 8
Analysis Framework
3,6,2,5,1,7,4 K =4
3,6,2,5,1,7,8 K =4
4,2,8,5,3,1,9 K=4
5,2,8,4,3,1,9 K=4
Does Algorithm efficiency depend on only input
size?
Department of Computer Science 8
What to Analyze?
where
n is the size of the input,
m is the number of groups,
Therefore
Logarithms
Since logarithms will play an important role in
our analysis, there are a few properties that
must be discussed.
The logarithm base y of a number x is the
power of y that will produce the number x.
Case 1: x = a[mid]
x = 10
low = 0, high = 8
mid = (0 + 8) / 2 = 4
a: 1 5 7 9 10 13 17 19 27
0 1 2 3 4 5 6 7 8
a: 1 5 7 9 10 13 17 19 27
0 1 2 3 4 5 6 7 8
a: 1 5 7 9 10 13 17 19 27
0 1 2 3 4 5 6 7 8
val = 7
a: 1 5 7 9 10 13 17 19 27
0 1 2 3 4 5 6 7 8
a: 1 5 7 9 10 13 17 19 27
0 1 2 3 4 5 6 7 8
a: 1 5 7 9 10 13 17 19 27
0 1 2 3 4 5 6 7 8
Department of Computer Science 36
Binary Search: Binary Tree
i = log2 N
Input size: n
Basic operation: A[i] = A[j]
Does C(n) depend on type of input?
Department of Computer Science 54
Example 9:
Basic Operation
Factorial
kcn < n! < nn
where k is some
constant, and c is a
constant less than n
O(1)
Time complexity of a function (or set of
statements) is considered as O(1) if it doesn’t
contain loop, recursion and call to any other
non-constant time function. For example
swap() function has O(1) time complexity.
T(n) = c1+c2+c3
= O(1)
O(loglogn)
Time Complexity of a loop is considered as
O(loglogn) if the loop variables is
reduced/increased exponentially by a constant.
O(loglogn)
Time Complexity of a loop is considered as
O(loglogn) if the loop variables is
reduced/increased exponentially by a constant.
O(logn)
Time Complexity of a loop is considered as
O(logn) if the loop variables is
divided/multiplied by a constant amount.
O(n)
Time Complexity of a loop is considered as
O(n) if the loop variables is
incremented/decremented by a constant
amount.
O(n)
Time Complexity of a loop is considered as
O(n) if the loop variables is
incremented/decremented by a constant
amount.
O(nc)
Time complexity of nested loops is equal to the
number of times the inner most statement is
executed.
O(n2)
O(nc)
Time complexity of nested loops is equal to the
number of times the inner most statement is
executed.
O(n2)
O(1)
A1
O(N)
A2
O(1)
Algorithm Example()
while(counter < n)
{
if(n%2 == 0)
{ O(N)
binarySearch(preSortedArray, counter);
}
}
The time efficiencies of a large number of algorithms fall into only a few
classes.
Basic Operation
n
T ( n) 2 2n O ( n)
i 1
Basic Operation
n
T ( n) 1 n O ( n)
i 1
Multiplication of two
Multiplication of two matrices
numbers
Visiting a vertex or
Typical graph problem
traversing an edge