lect1-1
lect1-1
Sorting and
Divide and Conquer
Lecture 1 Introduction to
Algorithm and Sorting
What is an Algorithm?
• An algorithm is a computational procedure
that takes some value, or a set of values,
as input and produces some values, or a
set of values, as output.
• So, it is a sequence of computational
steps that transform the input into the
output.
• Correction: sequence -> combination
Sequential and Parallel
• In sequential computation, an algorithm is
a sequence of computational steps.
Running time
2
Insert Sort O(n )
Merge Sort O(n log n)
f (n) O( g (n)) means
there exist constants c 0 and n0 0
such that
0 f (n) cg (n) for n n0 .
c1n 2 and c2 n log n, who is bigger?
2, 4, 5, 6, 1, 3 In the key outside of array.
How to calculate running time?
• Each “line” of pseudocode requires a
constant time. (In RAM model)
for j 2 to length[ A] This loop runs n-1 times
do begin and each time runs at most
4+3(j-1) lines.
key A[ j ];
i j 1;
while i 0 and A[i ] key
do begin This loop runs at most
j-1 times and each time
A[i 1] A[i ]; runs at most 3 lines.
i i 1;
end - while; T (n) j 2 (4 3( j 1))
n
Main Program
begin
Merge - Sort ( A,1, n);
end
Procedure
Merge - Sort ( A, p, r )
if p r
then begin q ( p r ) / 2;
Merge - Sort ( A, p, q );
Merge - Sort ( A, q 1, r );
Merge( A, p, q, r );
end - then.
5,2,7,4,6,8,1,3
5,2,7,4 6,8,1,3
5 2 7 4 6 8 1 3
2,4,5,7 1,3,6,8
1,2,3,4,5,6,7,8
Merge( A, p, q, r )
n1 q p 1;
n2 r q;
create array L[1..n1 1] and R[1..n2 1];
for i 1 to n1
do L[i ] A[ p i 1];
for j 1 to n2
do R[ j ] A[q j ];
L(n1 1) ; R (n2 1) ;
i 1;
j 1;
for k p to r
do if L[i ] R[ j ]
then A[k ] L[i ] and i i 1
else A[k ] R[ j ] and j j 1;
Example L : 2, 3, 5, 7, ; R : 1 , 4, 6, 8, ;
A : 1,
L : 2, 3, 5, 7, ; R :1, 4, 6, 8, ;
A :1, 2,
L : 2, 3, 5, 7, ; R :1, 4, 6, 8, ;
A :1, 2, 3,
L : 2, 3, 5, 7, ; R :1, 4, 6, 8, ;
A :1, 2, 3, 4,
L : 2, 3, 5, 7, ; R :1, 4, 6, 8, ;
A :1, 2, 3, 4, 5,
L : 2, 3, 5, 7, ; R :1, 4, 6, 8, ;
A : 1, 2, 3, 4, 5, 6,
L : 2, 3, 5, 7, ; R :1, 4, 6, 8, ;
A :1, 2, 3, 4, 5, 6, 7,
L : 2, 3, 5, 7, ; R :1, 4, 6, 8, ;
A :1, 2, 3, 4, 5, 6, 7, 8,
L : 2, 3, 5, 7, ; R :1, 4, 6, 8, ;
Procedure
Merge - Sort ( A, p, r ) T (n)
if p r
then begin q ( p r ) / 2;
T ( n / 2 )
Merge - Sort ( A, p, q );
Merge - Sort ( A, q 1, r ); T ( n / 2 )
Merge( A, p, q, r ); (n)
end - then.
T (n) 2T ( n / 2 ) (n)
f (n) ( g (n)) means
there exist constants 0 c1 c2 and n0 0
such that
0 c1 g (n) f (n) c2 g (n) for n n0 .
Symmetry
T (2 k 1 ) T (2 k 1 ) 2c2 2 k 1 c2 2 k
T (2 k 2 ) T (2 k 2 ) T (2 k 2 ) T (2 k 2 )
T (2 k ) c2 k 2 k
Substitution Method
• Guess the form of the solution (e.g., use
recursive tree).
• Use math induction to find the constants
and also show the solution works.
Solve T (n) 2T ( n / 2 ) (n)
lg n / 2 lg(n / 2 1 / 2)
lg(n / 2) lg(1 1 / n)
lg n 1 lg e1/ n (note : 1 x e x )
lg n 1 (lg e) / n
Where 10c2 comes from?