我写了一个shell脚本来对整数进行二进制搜索。它接受以空格分隔的整数数组,但是当代码继续执行并且我们输入要搜索的元素时,代码不会继续进行。它要么卡住了,要么正在接受更多的输入,而这两者都是不希望的。
这是代码:
#!/bin/bash
declare -a arr
echo "Enter space separated sorted integers:"
read -ra arr
declare -i search
echo -n "Enter the element to be searched for: "
read -r search
index=-1
beg=0
mid=0
last=${#arr[@]}
last=$((last - 1))
while [ $beg -le $last ]; do
mid=$((beg / 2 + end / 2))
if [ $mid -eq "$search" ]; then
index=$mid
break
elif [ $mid -gt "$search" ]; then
end=$((mid - 1))
elif [ $mid -lt "$search" ]; then
beg=$((mid + 1))
fi
done
if [ $index -ne -1 ]; then
echo "Element found at $index"
else
echo "Element not found"
fi
答案 0 :(得分:2)
好的,这是我在代码中发现的错误:
end
代替last
(感谢John Kugelman,EdmCoff和markp-fuso) mid=$((beg / 2 + last / 2))
的行为不会是 mid =(beg + last)/ 2 。有时,当beg,last = 5,beg / 2 + last / 2的结果为4而不是5。所以最终的工作代码如下:
#!/bin/bash
declare -a arr
echo "Enter space separated sorted integers:"
read -ra arr
declare -i search
echo -n "Enter the element to be searched for: "
read -r search
index=-1
beg=0
mid=0
last=${#arr[@]}
last=$((last - 1))
while [ $beg -le $last ]; do
echo -e "\nbeg=$beg\nmid=$mid\nlast=$last\n"
mid=$((beg + last))
mid=$((mid/2))
if [ "${arr[$mid]}" -eq "$search" ]; then
index=$mid
break
elif [ "${arr[$mid]}" -gt "$search" ]; then
last=$((mid - 1))
elif [ "${arr[$mid]}" -lt "$search" ]; then
beg=$((mid + 1))
fi
done
if [ $index -ne -1 ]; then
echo "Element found at $((index+1))"
else
echo "Element not found"
fi