30 March 2012

Shell Script for Bubble Sort

5 comments

Q. How do I write Bubble sort in Bash


Ans:

#!/bin/bash
echo "enter maximum number"
read n
# taking input from user
echo "enter Numbers in array:"
for (( i = 0; i < $n; i++ ))
do
read nos[$i]
done
#printing the number before sorting
echo "Numbers in an array are:"
for (( i = 0; i < $n; i++ ))
do
echo ${nos[$i]}
done
# Now do the Sorting of numbers
for (( i = 0; i < $n ; i++ ))
do
for (( j = $i; j < $n; j++ ))
do
if [ ${nos[$i]} -gt ${nos[$j]}  ]; then
t=${nos[$i]}
nos[$i]=${nos[$j]}
nos[$j]=$t
fi
done
done
# Printing the sorted number
echo -e "\nSorted Numbers "
for (( i=0; i < $n; i++ ))
do
echo ${nos[$i]}
done

Output



Enjoy :)


If You Liked This Post Please Take a Time To Share This Post

You May Also Like...

5 comments:

  1. You need to declare the array: declare -a nos to make the script work.

    ReplyDelete
  2. nthonnaadeeyyyy ithu.... poy pani panikkedaaaaa ********
    for(p=1;p<=n-1;p++) // Loop for Pass
    {

    for(j=1;j<=n-1;j++)
    {
    if(a[j]>a[j+1])
    {
    temp=a[j]; // Interchange Values
    a[j]=a[j+1];
    a[j+1]=temp;
    }
    }

    ReplyDelete
  3. this code is showing an error of " unary operator expected"

    ReplyDelete
  4. It was hard for me to imagine how nested loops works.
    Let run this script, may help for newbees like me.

    #!/bin/bash
    clear
    read -p "Give a number > 1 but <= 4: " n
    echo
    # I nested 3 for loop-s
    for ((i=1;i<=$n;i++))
    do
    echo "------------- $i. i loop ->"

    # ------------------->>
    for ((j=$i;j<=$n;j++))
    do
    tput setaf 1;
    echo " --------- $i/$j. j loop"
    tput sgr0

    # ------------------->>
    for ((f=$j;f<=$n;f++))
    do
    tput setaf 2;
    echo " ----$i/$j/$f. f loop"
    tput sgr0
    done
    # -----------------------------------------------
    done
    # -----------------------------------------------
    echo "------------- $i. i loop-ENDing >|"
    # read x # uncomment if you whant to see on the flow. Just hit
    echo
    done

    ReplyDelete