Professional Documents
Culture Documents
L03 Algorithms
L03 Algorithms
gr/courses/INF161/
2016 - I.
?
- 2016 - . - 03 - EXAMPLES ALG & COMPL 2
Example: GCD
gcd(100,1)
gcd(a,b)
: b>0 100 1
: a,b 99 1
while a <> b do 98 1
if a > b: a=ab 100
else: b=ba
return a 2 1
1 1
: a=b: O(1)
: a >1, b=1: O(a)
O(a)=O(2n )
(# bits): n = log a + log b 2 log a = O(log a)
H gcd(a,b) ( n)
?
- 2016 - . - 03 - EXAMPLES ALG & COMPL 3
Example: GCD - O(log )
Euclid(a,b) gcd(25,11) gcd(100,1)
: b>0 25 11 100 1
: a,b 11 3 1 0
if b=0: return a 3 2
return Euclid(b, a mod b) 2 1
1 0
if ba/2 then a mod b<b< a/2 if b >a/2 then a mod b=a-b < a/2
A: 2 4 5 7 A: 2 4 5 7
C=1 2 2 3 4 5 6 7
B: 1 2 3 6 B: 1 2 3 6
: (n)
, /
(n=p+q)
: 2n=(n), A = n ?
7
- 2016 - . - 03 - EXAMPLES ALG & COMPL
Example: Selection Sort - O(n2)
SelectionSort (A[1..n])
: [1..n]
:
for i=n,n-1,3,2:
find the position p of max element in A[1..i]
swap(A[p], A[i])
: (n2) i : max(A[1..n])
8
- 2016 - . - 03 - EXAMPLES ALG & COMPL
Insertion Sort - O(n2)
InsertionSort (A[1..n])
: [1..n]
:
for i=2 to n:
j = i
while (A[j]<A[j-1] and j>1):
swap (A[j], A[j-1])
j = j-1
: 5 12 7 20 6 3
5 12 7 20 6 3
5 7 12 20 6 3
5 7 12 20 6 3
5 6 7 12 20 3
3 5 6 7 12 20
9
- 2016 - . - 03 - EXAMPLES ALG & COMPL
Insertion Sort - O(n2)
InsertionSort (A[1..n])
: [1..n]
:
for i=2 to n:
j = i
while (A[j]<A[j-1] and j>1):
swap (A[j], A[j-1])
j = j-1
:
( )
(BEST CASE)
-
- 1 while for
- n-1 (i=2 to n)
- (n)
10
- 2016 - . - 03 - EXAMPLES ALG & COMPL
Insertion Sort - O(n2)
InsertionSort (A[1..n])
: [1..n]
:
for i=2 to n:
j = i
while (A[j]<A[j-1] and j>1):
swap (A[j], A[j-1])
j = j-1
:
( )
(WORST CASE)
-
- for (i=2 to n)
i while (j=i,i-1,2,1)
n n
n ( n 1)
- i i (n 2 )
i2 i 1 2
11
- 2016 - . - 03 - EXAMPLES ALG & COMPL
Insertion Sort - O(n2)
InsertionSort (A[1..n])
: [1..n]
:
for i=2 to n:
j = i
while (A[j]<A[j-1] and j>1):
swap (A[j], A[j-1])
j = j-1
:
( )
(VERAGE CASE)
(Expected)
(n2 )
12
- 2016 - . - 03 - EXAMPLES ALG & COMPL
(Sorting)
SelectionSort
InsertionSort
: (n2 )
: =
n O(log M)
log M =, .. log M =32
= O(n)
? : (n logn)
? !
n
Z ij X
k 1
ik Ykj
: O(n3)
: O(n3)
n x m m x q :
O(nmq)
? ,
p, q 0 p q n
q
V ( p, q ) A(i)
i p
, V ( p, q ) V ( p ' , q ' ), 1 p ' q' n
:
Year 1 2 3 4 5 6 7 8 9
Profit -3 2 1 -4 5 2 -1 3 -1
: V(5,8)=9
O(1)
:
||=k =
= O(nk) k:
Brute force
for S:
n ?
V=0
for x A: V=V+x : 2n
if V=M then return YES
return NO
|A|=O(n)
( n)
: O(n2n)
? (nM)