小编Nav*_*idk的帖子

递归和迭代二分搜索:哪个更有效,为什么?

我已经编写了递归和迭代二进制搜索的算法:

递归

AlgorithmBinSrch(a, i,l,x)
// Given an array a[i :l] of elementsin nondecreasing
// order,1<i <=l,determinewhetherx is present,and
// if so,return j suchthat x = a[j];elsereturn 0.
{
    if (l =i) // If Small(P) {
        if(x=a[i]) 
            return i;
        else 
            return 0;
    } else { // ReduceP into a smallersubproblem.
        mid:=[(i+l)/2]; 
        if (x = a[mid]) 
            return mid;
        else if (x <a[mid]) 
            returnBinSrch(a,i,mid-1,x);
        else
            returnBinSrch(a,mid1+,l,x);
    } 
}
Run Code Online (Sandbox Code Playgroud)

迭代

// Given an array a[1:n] of elementsin nondecreasing
// order,n >=0,determine whether x is …
Run Code Online (Sandbox Code Playgroud)

algorithm search pseudocode time-complexity

7
推荐指数
2
解决办法
3634
查看次数

标签 统计

algorithm ×1

pseudocode ×1

search ×1

time-complexity ×1