Search code examples
linuxshellunixsortingbubble-sort

Bubble sort in Linux/Unix shell scripting


I am trying to perform bubble sort is Unix shell script. Why is my code not working?

a=(10 8 20 25 12)

for ((i=0;i<5;i++))
do
 for((j=0;j<5;j++))
 do
if ((${a[j]} > ${a[$((j+1))]}))
then
  v=${a[$j]}
  a[$j]=${a[$((j+1))]}
  a[$((j+1))]=$v
    fi
 done
done
    echo ${a[*]}
    echo "end..."

Solution

  • I guess this is homework. therefore I don't give codes, just point out the errors in your codes:

    for((j=0;j<5;j++)) then read a[j+1], here would be problem because when j=4, j+1 doesn't exist

    fix that, your program will sort.