Professional Documents
Culture Documents
Ch05 Algorithms
Ch05 Algorithms
Ch05 Algorithms
5.1
5.2
5.3
5.4
5.5
5:
:
, ,
, ,
.
5:
-
- ;
- (, )
- :
-
-
-
5:
:
.
.
.
.
5:
1. .
2. ( )
.
3.
.
4.
.
5:
.
,
:
.
- .
.
.
5:
(1) (1.1)
(1.2)
(1.3)
(1.4)
(2)
(3)
(1.1.1)
(1.1.2)
(1.1.3)
(1.1.4)
(1.3.1)
(2.1)
(2.2)
(2.3)
(2.4)
(2.1.1)
(2.1.2)
(2.4.1)
(2.4.2)
(3.1)
5:
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
;
,
; 1000 ,
, ;
5:
:
--
-- ( )
-- ( )
= false
(test)
= false
= true
5:
false
(test)
true
5:
10
false
if condition then P1
false
true
P1
P2
true
P1
11
false
false
true
P2
true
false
P1
true
P1
P2
P3
P4
12
(while)
5:
13
(repeat)
5:
14
()
() ()
() ()
(
)
5:
15
3;
( >0)
(
-1)
5:
16
Fred, Alex, Diana, Byron, Carol
1 2
1+ 2 + 3 + + (n 1) = (n n)
2
: , ,
5:
17
5:
18
()
2
( )
( - .
,
.
( ,
)
(
, )
.
+ 1
)
5:
19
:
:
,
factorial(N)
1*2*3*... (N-1)*N
N*factorial(N-1)
module factorial(N)
3
if N=1
then answer = 1
else answer = N * factorial(N-1)
3*
5:
2*
20
: Hanoi
:
,
.
64
:
: 64 a b ( )
: 63 a c,
a b,
63 c b.
5:
21
: Hanoi (2)
64
_ (, , , )
module _ (, a, b, c)
if N=1
then 1 a b
else { _ (-1, a, c, b);
1 a b;
_ (-1, c, b, a) }
5:
22
: Hanoi (3)
module _ (, a, b, c)
if N=1
then
else { _ (-1, a, c, b);
1 ;
_ (-1, c, b, a) }
3
2
1
_ (3, a, b, c)
_ (2, a, c, b)
1,a,b
_ (2, c, b, a)
2,a,c
_ (1, a, b, c)
1,a,b
2,c,b
_ (1, b, c, a)
_ (1, c, a, b)
_ (1, a, b, c)
1,b,c
1,c,a
1,a,b
5:
23
(, )
( )
( )
[ .
.
1: =
( .)
2: <
(
,
.)
3: >
(
,
.)
]
5:
24
Binary search
low = 0; high = N-1;
BinarySearch(A[0..N-1], value, low, high) {
if (high < low)
return -1 // not found
mid = (low + high) / 2
if (A[mid] > value)
return BinarySearch(A, value, low, mid-1)
else
if (A[mid] < value)
return BinarySearch(A, value, mid+1, high)
else
return mid // found }
5:
25
5:
26
Log2 n = n 2
5:
log n
=n
27
.
(n2)
, .
5:
28
f (n ) O(g (n )) : f g
n , f (n ) g (n ) k
f g
f (n ) (g (n )) : f g
f g, (g)
29
( )
5:
30
( )
5:
31