SOURCE

console 命令行工具 X clear

                    
>
console
/*
  算法的概念:算法是解决特定问题求解步骤的描述,在计算机中表现为指令的有限序列,并且每条指令表示一个或多个操作。
*/

// 用两种方式来实现求裴波那契数列第n项的值,一种方式用递归方式,第二种方式用普通循环方式。

/*
    链接:https://www.cnblogs.com/tandaxia/p/10919609.html
    链接:https://www.jb51.net/article/167003.htm
*/

function recursionFbi(n) {  // 递归方式
    if (n < 3) return(1);
    if (n === 3) return(2);
    return recursionFbi(n-1) + recursionFbi(n-2);
}

function circleFbi(n) { // 循环方式
 document.getElementById('resStart').innerText = (new Date()).getTime();
  if (n < 3) return 1;
  let a = 1, b = 1, c = 0;
  for (let i = 0; i < n; i++) {
    if (i > 1) {
      c = a + b;
      a = b;
      b = c;
    }
  }
  return c;
}

let resn = '';
document.getElementById('input').onchange = function() {
  resn = this.value;
}
function btnClick(fun) {
  new Promise((resolve, reject) => {
    document.getElementById('resStart').innerText = (new Date()).getTime();
    resolve(fun(resn));
  }).then(res => {
    document.getElementById('res').innerText = res;
    document.getElementById('resEnd').innerText = (new Date()).getTime();
    document.getElementById('resTime').innerText = document.getElementById('resEnd').innerText - document.getElementById('resStart').innerText;
  })
}

document.getElementById('btn1').onclick = function() {
    btnClick(recursionFbi);
}

document.getElementById('btn2').onclick = function() {
    btnClick(circleFbi);
}

// 上面通过两种方式求裴波那契数列,表现出来的时间损耗值相差惊人!

/*
    1、JS数据结构--算法复杂度一般是有时间复杂度和空间复杂度组成的。
    2、T(n) = O(f(n))[时间复杂度公式]--f(n)表示一行代码执行的次数
    3、S(n) = O(f(n))[空间复杂度]
    4、时间复杂度看的是代码的执行时间的趋势,空间复杂度就是指的占用内存的趋势(无论是时间还是
       空间复杂度,代表的都是一种趋势)。
    5、就是规模比较大的时候,那些常量是起不到决定性的作用的,所以这个时候我们忽略这些常量。
*/
<html>
<title>JS数据结构--算法之复杂度判断</title>
<style>
    button {
        cursor: pointer;
    }
</style>
<body>
    <p>1、求裴波那契数列第n项的值:</p>
    <p>
        <input type="text" id="input" value="">
        <button id="btn1">递归算法</button>
        <button id="btn2">循环算法</button>
    </p>
    <p>
        结果:<span id='res'></span>
    </p>
    <p>
        开始时间戳:<span id='resStart'></span>
    </p>
    <p>
        结束时间戳:<span id='resEnd'></span>
    </p>
    <p>
        耗时:<span id='resTime'></span>
    </p>
</body>
</html>