?an?cnlogn MERGE(low,mid,high);
endif
end MERGESORT
递归方程
2
T(n)???2T(n/2)?cn
k
设n=2
解递归方程:
?an?1n?1
2、 procedure S1(P,W,M,X,n)
i←1; a←0
while i≤ n do
if W(i)>M then return endif a←a+i i←i+1 ; repeat end
i←1 ;s←0 时间为:O(1)
while i≤ n do 循环n次 循环体内所用时间为 O(1) 所以 总时间为:
T(n)=O(1)+ nO(1)= O(n)
3、procedure PARTITION(m,p)
Integer m,p,i;global A(m:p-1) v←A(m);i←m
loop
loop i←i+1 until A(i) ≥v repeat
loop p←p-1 until A(p) ≤v repeat
if i
then call INTERCHANGE(A(i),A(p)) else exit endif
repeat
A(m) ←A(p);A(p) ←v End PARTITION
最多的查找次数是p-m+1次
4、procedure F1(n)
if n<2 then return(1) else return(F2(2,n,1,1)) endif
end F1
procedure F2(i,n,x,y) if i≤n
3
then call F2(i+1,n,y,x+y) endif
return(y) end F2
F2(2,n,1,1)的时间复杂度为:
T(n)=O(n-2); 因为i≤n时要递归调用F2,一共是n-2次
当n=1时F1(n)的时间为 O(1)
当n>1时F1(n)的时间复杂度与F2(2,n,1,1)的时间复杂度相同即为为 O(n) 5、procedure MAX(A,n,j) xmax←A(1);j←1 for i←2 to n do
if A(i)>xmax then xmax←A(i); j←i;endif repeat
end MAX
xmax←A(1);j←1 时间为:O(1) for i←2 to n do 循环最多n-1次
所以 总时间为: T(n)=O(1)+ (n-1)O(1)= O(n)
6、procedure BINSRCH(A,n,x,j) integer low,high,mid,j,n; low←1;high←n
while low≤high do
mid←|_(low+high)/2_| case
endcase repeat j←0
end BINSRCH log2n+1
三、 算法理解
1、写出多段图最短路经动态规划算法求解下列实例的过程,并求出最优值。
1 3 6 8 2 5 4