[upon request] Shell Program for Binary Search

echo "enter the size of the array"
read n
echo "enter the array elements"
for((i=0;i<n;i++))
do
 read a[i]
done
echo "sorted array"
for((i=0;i<n;i++))
do
 for((j=0;j<n;j++))
 do
  if [ ${a[i]} -lt ${a[j]} ]
  then
   t=${a[i]}
   a[$i]=${a[j]}
   a[$j]=$t
  fi
 done
done
for((i=0;i<n;i++))
do
 echo ${a[i]}
done
echo "enter the search element"
read numb
u=$((n-1))
l=0
s=0
while [ $l -le $u ]
do
 mid=$((($l + $u ) / 2))
 if [ $((a[mid])) -eq $numb ]
 then
  echo element found at $((mid+1))
  s=1
  break

  elif [ $((a[mid])) -lt  $numb ]

  then
  l=$(($mid+1))
 else
  u=$(($mid-1))
 fi
done
if [ $s -eq 0 ]
then
 echo element not found
fi

No comments:

Post a Comment