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));