簡體   English   中英

為什么我的二進制搜索腳本在輸入后沒有繼續執行?

[英]Why is the execution of my binary search script not proceeding after input?

我寫了一個 shell 整數二進制搜索腳本。 它接受以空格分隔的 integer 數組,但是當代碼繼續執行並且我們輸入要搜索的元素時,代碼不會繼續執行。 它要么被卡住,要么正在接受更多輸入,這兩種情況都是不受歡迎的。

這是代碼:

#!/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

好的,這是我在代碼中發現的錯誤:

  1. 使用end而不是last (感謝 John Kugelman、EdmCoff、markp-fuso)
  2. 從來沒有像 Array[index] 那樣實際比較 Array 值(感謝 markp-fuso)
  3. 有時, mid=$((beg / 2 + last / 2))不會表現為mid=(beg + last)/2 有時,當 beg, last=5 時,beg/2 + last/2 將計算為 4 而不是 5。
  4. 最后但同樣重要的是,在調試中使用 echo 總是有幫助的, (感謝 chepner )

所以最終的工作代碼看起來像:

#!/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