ChenPt / dailyNote

dailyNode for myself
https://github.com/ChenPt/dailyNote/issues
0 stars 0 forks source link

2018/07/18 二分查找法 & 阶乘 #18

Open ChenPt opened 6 years ago

ChenPt commented 6 years ago
let find_half = (value, arr) => {
  let half = Math.floor(arr.length/2)
  let test
  if(value === arr[half]) {
    console.log("find the value in the array; it's index is :", half)
    return half
  }
  test = value < arr[half] ? arr.slice(0, half) : arr.slice(half, arr.length)
  return find_half(value, test)
}

// 测试用例
// arr必须是有序的才可以使用二分查找
find_half(5, [1,2,3,4,5,6])
ChenPt commented 6 years ago

阶乘递归实现

let factorial = (num) => {
  if(num === 1) return 1
  return num * factorial(num-1)
}

阶乘迭代实现

let factorial2 = (num) => {
  let res = 1
  for(let i = 1; i <= num; i++) {
    res = i * res
  }
  return res
}
ChenPt commented 6 years ago

斐波那契数列

迭代实现

let fib1 = () => {

}