[英]Why is the execution of my binary search script not proceeding after input?
I wrote a shell script for binary search of integers.我写了一个 shell 整数二进制搜索脚本。 It's accepting space separated integer array, but when the code proceeds and we input the element to be searched, the code doesn't proceed further.
它接受以空格分隔的 integer 数组,但是当代码继续执行并且我们输入要搜索的元素时,代码不会继续执行。 It is either stuck or it is accepting more inputs, both of which is undesired.
它要么被卡住,要么正在接受更多输入,这两种情况都是不受欢迎的。
Here's the code:这是代码:
#!/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
Ok, so here are the errors I found in my code:好的,这是我在代码中发现的错误:
end
instead of last
(Thanks to John Kugelman, EdmCoff, markp-fuso)end
而不是last
(感谢 John Kugelman、EdmCoff、markp-fuso)mid=$((beg / 2 + last / 2))
won't behave as mid=(beg + last)/2 .mid=$((beg / 2 + last / 2))
不会表现为mid=(beg + last)/2 。 Sometimes when beg, last=5, beg/2 + last/2 will evaluate in 4 instead of 5. So final working code looks like:所以最终的工作代码看起来像:
#!/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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.