zoukankan      html  css  js  c++  java
  • 《Algorithm in C》by Sedgewick 读书笔记

    Update: July 4, 2014

    Chap 5:

    At the beginning, he mentioned that: recursion is a divide-and-conquer method. Although many algorithms can be solved in simple recursion but it is often an equally algorithm lies in the details of a nonrecursive implementation?(没搞懂)

    Divide-and-conquer programs normally do not reduce to trivial loops since they have 2 recursive calls and do had divided without overlap so no excessive recomputing.

    /*
    * method 1 of ruler: @ p54
    */
    
    rule(int l, int r, int h){
       ...
       mark(m,h);
       rule(l, m, h-1);    // NOTICE: not to m-1;
       rule(m, r, h-1);   // NOTICE: not from m+1;
    }

    as shown in Fig 5.4. The tree plot of calling recursive method. shows the difference of changing the order of calling 2 recursions.

    In compiler, it actually removes recursion. One well-known tech is end-recursion removal. Firstly use goto instead of looping. Then remove the 2nd recursion (this is easy since there is no code after it). But the other recursion needs more work to remove, which is by using the normal way for any procedure call:“push the values of local variables and the address of the next instruction on a stack, set the values of parameters to the procedure and goto the beginning of the procedure.” Then, when the procedure has completes, it must “pop the return address and values of local variables from stack(注意顺序,因为stack是LIFO), reset the variables, and goto the return address.”

    This is the same as the way Sedgewick's code:

    traverse(struct node *t){
    l:   if(t==z) goto s;
        visit(t);
        push(t); t=t->l; goto l;  // when call procedure, push var, return addr into stack. Then 
                   // change the var and goto the begining of the procedure. Also, when complete 
                  // it should go to s, which pop var and goto return addr.
    r:  t = t->r; goto l;         
    s: if(stackEmpty()) goto x;  // when complete, it pop return addr, var out and goto the return addr.
        t = pop(); goto r;            // since the return addr is the ending recursive which is a constant, so 
    x: ;                 // don't need to push or pop the addr. Also,
    
    }
  • 相关阅读:
    菜鸟二三事
    访问 IIS 元数据库失败的问题(转)
    SQL Server 2005/2008还原数据库时遇到的问题(转)
    ME54N审批、撤批触发增强点:ME_RE…
    南通网站建设整理:最新搜索引擎登录口保证都可以用
    调试mvc的源代码
    c#委托(delegate)揭秘
    ASP.NET 应用程序生命周期概述
    JavaScript Array(数组)对象
    jQuery.each
  • 原文地址:https://www.cnblogs.com/gpuasic/p/3825456.html
Copyright © 2011-2022 走看看