Home > database >  Bash - Mistake of Bubble sort for arguments
Bash - Mistake of Bubble sort for arguments

Time:10-07

Have to sort arguments using Bubble Sort.

#!/bin/bash

myArray=( "$@" )

for((i = 0; i<${#myArray[@]}; i  ))
do
    
    for((j = i; j<${#myArray[@]}-i-1; j  ))
    do
    
        if [[ ${myArray[j]} > ${myArray[$((j 1))]} ]]
        then
            temp=${myArray[j]}
            myArray[$j]=${myArray[$((j 1))]}  
            myArray[$((j 1))]=$temp
        fi
    done
done

for i in ${myArray[@]}; do
    echo $i;
done

Tried to input d c b a. Output: a b c d. Tried to input a b c d. Output: c a b d. Where is mistake?

CodePudding user response:

The 2nd loop should start at 0:

#!/bin/bash

myArray=( "$@" )
for((i=0; i<${#myArray[@]}; i  ))
do
    for((j=0; j<${#myArray[@]}-i-1; j  ))
    do
        if [[ ${myArray[j]} > ${myArray[$((j 1))]} ]]
        then
            temp=${myArray[j]}
            myArray[$j]=${myArray[$((j 1))]}  
            myArray[$((j 1))]=$temp
        fi
    done
done

for i in ${myArray[@]}; do
    echo $i;
done
  • Related