100层楼 测试鸡蛋在那一楼坏(最多7次)

var flag = 0
function binnaryFun(arr, num) {
  flag++
  let len = arr.length;
  let middleIndex = parseInt(len / 2)
  let middleNumber = arr[middleIndex-1]
  console.log('midddleNumber', middleNumber)
  
  if(middleNumber === num) {
    return middleNumber
  } else if(middleNumber > num) {
    let restArr = arr.slice(0, middleIndex)
    return binnaryFun(restArr, num)
  } else if(middleNumber < num) {
    let restArr = arr.slice(middleIndex)
    return binnaryFun(restArr, num)
  }
}
let arr = []
for(let i=1; i<101; i++) {
  arr.push(i)
}
let result = binnaryFun(arr, 75)
console.log('次数:', flag)

 

posted @ 2020-08-14 11:26  巫瞅瞅  阅读(201)  评论(0编辑  收藏  举报