linux下shellscript实现二分查找

#!/bin/bash
#program:calulate the times to find "k" in 1-n
#history:2016-2-26 MissZhou first release
PATH=/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/bin:/usr/local/sbin:~/bin
export PATH
function find()
{
        declare -i low=1
        declare -i high=$(($1))
        declare -i mid
        declare -i res=0
        declare -i fn=$(($2))
        while [  $low -lt  $high  ]
        do
                mid=$(($high/2+$low/2))
                res=$(($res+1)) 
                if [ $mid -lt $fn ] ; then
                low=$(($mid+1))
                else
                high=$(($mid-1))
                fi
                echo "$mid";
        done
        echo "find $res times"
}
read -p "input range " n
read -p "input found " k
find n k 


一晚上的成果~所以说,新学一门语言还是得自己写例子^_^
全部评论

相关推荐

10-16 15:48
算法工程师
点赞 评论 收藏
分享
09-17 10:53
四川大学 C++
牛客91242815...:会写标书没有任何卵用,鉴定为横向垃圾导师的受害者
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务