Algorithm Introduction
Algorithm Introduction
NYAB Talk 6
Algorithm
An algorithm is a sequence of instructions that one
must perform in order to solve a well-formulated
problem.
Problem ?
Input Output
?
Well-formulated Problem ? Unambiguous
precise
Why do we study algorithms?
RecursiveFibonacci(n)
if n = 1 or n = 2
return 1
else
a RecursiveFibonacci(n-1)
b RecursiveFibonacci(n-2)
return a + b
Recursion Tree
n
n-1 n-2
O(n) time
Algorithm Analysis
Correctness
Performance
Algorithm Correctness
?
Proving the correctness of an algorithm is not at all an easy
task. It consists of two steps
max a1
for i = 2 to n {
if (ai > max)
max ai
}
22
Linear Time: O(n)
• Merge. Combine two sorted lists
• A = a1,a2,…,an with B = b1,b2,…,bn into sorted
whole.
i = 1, j = 1
while (both lists are nonempty) {
if (ai bj) append ai to output list and increment i
else append bj to output list and increment j
}
append remainder of nonempty list to output list
23
Quadratic Time: O(n ) 2
• O(n3) solution. For each pairs of sets, determine if they are disjoint.
foreach set Si {
foreach other set Sj {
foreach element p of Si {
determine whether p also belongs to Sj
}
if (no element of Si belongs to Sj)
report that Si and Sj are disjoint
}
}
25
Polynomial Time: O(n ) Time k
• Independent set of size k. Given a graph, are there k nodes such that no two
k is a constant
are joined by an edge?