Showing posts with label shell script to display the position of an element in an array. Show all posts
Showing posts with label shell script to display the position of an element in an array. Show all posts

Thursday, 4 April 2019

Shell script to perform linear search in an array

#Check whether a number is present or not
echo -n "Enter limit n: "
read n
for((i=0;i<n;i++))
do
 read a[$i]
done
echo ${a[*]}
echo -n "Enter number to be searched: "
read key
pos=0
for((i=0;i<n;i++))
do
  if test $key -eq ${a[$i]}
  then
      pos=`expr $i + 1`
      break;
  fi
done
if test $i -ge $n
then
  echo "Number not found"
else
  echo "Number [$key] found at position $pos"
fi





OUTPUT
Safi>bash numsrch.sh
Enter limit n: 5
7
6
8
5
9
7 6 8 5 9
Enter number to be searched: 7
Number [7] found at position 1