Advertisement
Shailrshah

Linear Search

Nov 2nd, 2014
256
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.56 KB | None | 0 0
  1. #! /bin/bash
  2.  
  3. echo "Enter an array of elements, each separated by a space"
  4. read -a a
  5. n=${#a[@]}              #n denotes number of elements in the array
  6.  
  7. echo "Enter the number to search for: "
  8. read key                #key is the value that will be searched in the array
  9.  
  10. for(( i=0; i<$n; i++ ))         #loop for searching key in an array
  11. do
  12.     if [ $key == ${a[$i]} ]; then   #if key and element no. i are same, element has been found
  13.         break
  14.     fi
  15. done
  16.  
  17. if [ $i -lt $n ]; then          #if i < n, it means break statement had been encountered
  18.     echo "Found at position "$i
  19.     else echo "Not Found!"
  20. fi
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement