Search Here

Shell Script to implement Binary search on an array of n given elements


echo -e "\n\t\tBINARY SEARCH"  
echo -e "Enter the size of the array:\c"
read n
if (( n<1 ))
then
    echo -e "\nArray size can not be Zero or Negative"
    exit
fi
echo -e "\nEnter the array elements in ascending order\n"
for (( i=1;i<=n;i++ ))
do
    read arr[$i]
done
echo -e "\nThe array elements are\n"
for (( i=1;i<=n;i++ ))
do
    echo ${arr[$i]}
done
echo -e "\nEnter the element to search:\c"
read key
(( low=1  ))
(( up=n ))

while (( low<=up ))
do
    (( mid=(low+up)/2 ))
    if (( key==arr[mid] ))
    then
        echo -e "\nItem found at position $mid"
        exit
    elif(( key<arr[mid] ))
    then
        (( up=mid-1 ))  
    else
        (( low=mid+1 ))      
    fi          
done
echo -e "\nItem not found"

No comments:

Post a Comment