I wrote a shell script for binary search of integers. 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. 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