当前位置:文档之家› 算法设计技巧与分析 沙特 递归分治部分答案

算法设计技巧与分析 沙特 递归分治部分答案

end if
end count
递归出口high<low ?
6.51
EX6_51
输入:
输出:
h=high(R)
return h
end EX6_51
过程high(T)
//
if T为空then return -1
else
left=high(T->left);
right=high(T->right);
return 1+max{left,right}
5.33
算法:EX5_33
输入:已排序的数组A[1,…,n],整数x
输出:如果A中存在两个数,它们的和是x,则输出这两个数,若不存在,则输出none
find(程:find(s,t)
//确定A[s,…,t]中是否存在两个数,它们的和是x,如果存在则输出这两个数,若不存在,则输出none
return x1,x2,y1,y2中最大和最小元素对;
return (a[high],a[low]);
else return (a[low],a[high]);
end if
end if
end if
mid=(low+high)/2;
(x1,x2)=secondvalue(low,mid,a);
(y1,y2)=secondvalue(mid+1,high,a);
end find
6.6
EX6_6
输入:
输出:
num=count(1,n,x);
end EX6_6
过程count(low,high,x)
//
if high=low then
if A[low]=x then return 1
else return 0
else
mid=(low+high)/2
return count(low,mid)+count(mid+1,high)
if s=t then output none;
elseif s<t then
if A[s]+A[t]=x then
output A[s],A[t];
else if A[s]+A[t]>x then find(s,t-1);
else A[s]+A[t] find(s+1,t);
end if
end if
end if
end high
递归出口T->left == null and T->right==null then return 0 ?
全局变量?
6.52
算法SECONDVALUE
输入:正整数n和存储n个元素的数组a[1..n]
输出:数组a的第二大元素
(x1,x2)=secondvalue(1,n,a);
return x2;
end SECONDVALUE
过程secondvalue(low,high,a)
//返回数对(x1,x2)其中x1>=x2
if high-low=0 then
return (a[low],-∞); //这个地方有修改
else if high-low=1 then
if a[high]>=a[low] then
相关主题