用shell教你搞定各种查找算法-二分查找


main(){
  local nums=(1 2 4 5 6 7 8 100)

  local low=0;
  local high="${#nums[@]}"
#   local mid=$(((low+high)/2))
  local target=100;

  while [[ $low -le $high ]];do
    let cha=(high-low)/2
    let mid=low+cha

    local midNum=${nums[mid]};
    if [[ ${midNum} -eq ${target} ]];then
      echo "${mid}"
      return;
    fi

    if [[ ${midNum} -lt ${target} ]];then
      low=mid+1
    fi

    if [[ ${midNum} -gt ${target} ]];then
      high=high-1
    fi
  done
}

评论