遞歸 recursion

Someone in a movie theater asks you what row you're sitting in. You don't want to count, so you ask the person in front of you what row they are sitting in, knowing that you will respond one greater than their answer.

The person in front will ask the person in front of them.

This will keep happening until word reaches the front row, and it is easy to respond: "I'm in row 1!"

From there, the correct message (incremented by one each row) will eventually make its way back to the person who asked.

Why is this a good explanation?

It gets across three points:

There are some questions that may be inherently recursive and that some questions are easier to solve recursively.
The question I am asking ("what row am I in?") can be rephrased recursively as: "how many people are in front of me + 1?" with a base case of zero people in front of me.
It also illustrates the idea of a recursive call stack and how calls are pushed on then popped off the stack.

查字典

用字典查一個不明白的詞,在解釋中如果仍然有不理解的詞,繼續查第二個詞,依此進行下去,直到這個查到詞的解釋可以完全理解后,這樣遞歸走到了盡頭,往回走逐個理解上一個詞。最終就能理解最開始那個詞的意思了。

strike through

快速排序
function Qsort($arr)
{
  $len = count($arr);
  if ($len < 2)
  {
    return $arr;
  }

  $low = $high = [];
  $val = $arr[0];

  // 第一個元素為作為比較大小的基準值
  for ($i=1; $i<$len; $i++)
  {
    if ($arr[$i] < $val)
    {
      $low[] = $arr[$i];
    }
    else 
    {
      $high[] = $arr[$i]; 
    }
  }

  /**
  *  第 1 波                                       
  *      low []     ~ val 11     ~ high [31, 22, 25, 20, 100]
  *
  *  第 2 波(上次的 high 排序) 
  *      low [22, 25, 20]     ~ val 31     ~ high [100]
  *
  *  第 3 波(上次的 low 排序)
  *      low [20]     ~ val 22     ~ high [25]
  *
  *  完成排序,返回
  */
  $low = Qsort($low);
  $high = Qsort($high);

   return array_merge($low, [$val], $high);
}

$arr = [11, 31, 22, 25, 20, 100];

var_dump(Qsort($arr));

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容