Search code examples
arraysbashshellbubble-sort

Bubble Sort Shell, no output


I'm having a problem where I am trying to use bubble sort in shell, I am not really sure where my problem is occurring as I am assuming that my sorting is correct. I am not getting an error but I am not sorting the numbers at all.

#!/bin/bash

array=( "$@" )
#echo ${array[@]} print all elements in the array

if [ $# -gt 9 ]
then
    echo Too many arguments, run the program over again
    exit
fi

j=0
flag=1
a=${#array[@]}

for((j=0;j < $a - 1 && flag==1 ;j++))
do
flag=0
for((i=0; i< $a-j-1; i++))
do
    x=${array[$i]}
    y=${array[$i+1]}
if ((x>y))
then
    flag=1
    export temp=$x 
    export x=$y 
    export y=$temp
fi
done
done

echo "Sorted Array: " ${array[@]}

Solution

  • As pointed out in the comments, you swap the variables x and y but never any array entries. Instead of

    x=${array[$i]}
    y=${array[$i+1]}
    if ((x>y)); then
        flag=1
        export temp=$x 
        export x=$y 
        export y=$temp
    fi
    

    write

    x=${array[$i]}
    y=${array[$i+1]}
    if ((x>y)); then
        flag=1
        array[$i]="$y"
        array[$i+1]="$x"
    fi