《Algorithm in C》by Sedgewick 讀書筆記

來源:互聯網
上載者:User

標籤:style   blog   color   2014   cti   for   

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,}
相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.