Advertisement
Shailrshah

Binary Search

Oct 19th, 2014
281
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 0.87 KB | None | 0 0
  1. #!/bin/bash
  2. printArray(){
  3.         echo ${a[*]}
  4. }
  5. exchange(){
  6.         temp=${a[$1]}
  7.         a[$1]=${a[$2]}
  8.         a[$2]=$temp
  9. }
  10. bubbleSort(){
  11.         for (( i=0; i<$n; i++ ))
  12.         do
  13.             for(( j=$i; j<$n; j++ ))
  14.             do
  15.               if [ ${a[i]} -gt ${a[j]} ]
  16.                 then exchange $i $j
  17.               fi
  18.             done
  19.         done
  20. }
  21. binarySearch(){
  22.     l=0
  23.     ans=0
  24.     u=$(($n-1))
  25.     while [ $l -le $u ]
  26.     do
  27.         mid=$(((( $l+$u ))/2 ))
  28.         if [ $s -eq ${a[$mid]} ]
  29.         then
  30.             ans=1
  31.             break
  32.         elif [ $s -lt ${a[$mid]} ]
  33.             then u=$(($mid-1))
  34.         else l=$(($mid+1))
  35.         fi
  36.     done
  37.     if [ $ans -eq 1 ]
  38.         then echo "Element found at position $(($mid+1))"
  39.         else echo "Element not found"
  40.     fi
  41. }
  42. echo "Enter the numbers to be sorted:-"
  43. read -a a
  44. n=${#a[@]}
  45. bubbleSort
  46. printArray
  47. echo -n "Enter the element to be searched:"
  48. read s
  49. binarySearch
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement