J.John
J.John

Reputation: 369

How to swap array element in bash shell linux?

I have a problem regarding about the syntax on how to swap the element value in an array.

array="5 3 2 1 4"
echo "${array[*]}"

changed=1
while [ $changed != 0 ]
do
    changed=0
    for (( i=0 ; i<=${#array[@]}-1 ; i++ )) 
    do
        if [ ${array[$i]} -gt ${array[$i+1]} ]
            then
                tmp=${array[$i]}
                array[$i]=${array[$i+1]}
                array[$i+1]=$tmp
                changed=1
        fi
    done    
done

echo "Sorted array: "
echo "${array[*]}"

Edit:

Thanks for answering my question. I have changed the code, and now and it looks something like this.

But unfortunately there is still a problem.

It says:

jdoodle.sh: line 3: $'\r': command not found
jdoodle.sh: line 8: syntax error near unexpected token `$'\r''
jdoodle.sh: line 8: `    for ((i=0;i<=${#array[@]}-1;i++))

Upvotes: 4

Views: 3902

Answers (2)

PesaThe
PesaThe

Reputation: 7509

This is one implementation of bubble sort:

#!/bin/bash
array=(5 3 2 1 4)
echo "${array[*]}"

size=${#array[@]}

for (( i=0; i<size-1; i++ )); do

   for (( j=0; j<size-i-1; j++ )); do
      if (( array[j] > array[j+1] )); then
         tmp=${array[j]}
         array[j]=${array[j+1]}
         array[j+1]=$tmp
      fi
   done

done

echo "Sorted array:"
echo "${array[*]}"

Major problem with your code is that it actually does not use arrays.

Define arrays like array=(value1 value2 value3). It's also better to use [[ ]] for testing instead of [ ]. If we were to change your code just a little to also create a functioning bubble sort algorithm, it could look like this:

#!/bin/bash
array=(5 3 2 1 4)
echo "${array[*]}"

changed=1 j=0

while [[ $changed != 0 ]]
do
    ((j++))
    changed=0
    for (( i=0; i<${#array[@]}-j; i++ )) 
    do  
        if [[ ${array[i]} -gt ${array[i+1]} ]]
        then
           tmp=${array[i]}
           array[i]=${array[i+1]}
           array[i+1]=$tmp
           changed=1
        fi  
    done        
done

echo "Sorted array:"
echo "${array[*]}"

Upvotes: 3

Ljm Dullaart
Ljm Dullaart

Reputation: 4979

I do not get the \r messages, even in your test environment; in general, they are a result of DOS/Windows combatability (with a b).

Since this is obviously a tutorial example (why else would someone do bubblesort), some remarks about the code.

array="5 3 2 1 4"

does not create the array that you want. It creates a string. What you are looking for is:

array=(5 3 2 1 4)

The last element of the array is ${#array[@]}-1. Element counting starts at 0. So your for-loop should be:

for (( i=0 ; i<=${#array[@]}-2 ; i++ )) 

-2 because you're referencing ${array[$i+1]}, which would otherwise be outside the boundary.

Upvotes: 1

Related Questions