简体   繁体   English

为什么我的二进制搜索脚本在输入后没有继续执行?

[英]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:好的,这是我在代码中发现的错误:

  1. using end instead of last (Thanks to John Kugelman, EdmCoff, markp-fuso)使用end而不是last (感谢 John Kugelman、EdmCoff、markp-fuso)
  2. Never actually comparing Array values as in Array[index] (Thanks to markp-fuso)从来没有像 Array[index] 那样实际比较 Array 值(感谢 markp-fuso)
  3. sometimes, 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.有时,当 beg, last=5 时,beg/2 + last/2 将计算为 4 而不是 5。
  4. Last but not least, using echo in debugging always helps, (Thanks to chepner )最后但同样重要的是,在调试中使用 echo 总是有帮助的, (感谢 chepner )

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM