30 March 2012

Shell Script for Bubble Sort

4 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...

4 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