Sorting an array in Bash using Bubble sort

Prerequisite : Bubble Sort
Given an array arr sort the array in ascending order using bash scripting.

Examples:

Input : 9 7 2 5
Output :
Array in sorted order :
2 5 7 9



Approach :
For sorting the array bubble sort is the simplest technique. Bubble sort works by swapping the adjacent elements if they are in wrong order .
Example:

Given array - (9, 7, 2, 5)
After first iteration - (7, 2, 5, 9)
After second iteration - (2, 5, 7, 9)
and so on...

In this way, the array is sorted by placing the greater element at the end of the array .

filter_none

edit
close

play_arrow

link
brightness_4
code

# Sorting the array in Bash 
# using Bubble sort
  
# Static input of Array
arr = (10 8 20 100 12)
  
echo "Array in original order"
echo ${arr[*]}
  
# Performing Bubble sort 
for ((i = 0; i<5; i++))
do
      
    for((j = i; j<5-i-1; j++))
    do
      
        if ((${arr[j]} > ${arr[$((j+1))]}))
        then
            # swap
            temp = ${arr[$j]}
            arr[$j] = ${arr[$((j+1))]}  
            arr[$((j+1))] = $temp
        fi
    done
done
  
echo "Array in sorted order :"
echo ${arr[*]}

chevron_right


Output :

Array in sorted order :
8 10 12 20 100


My Personal Notes arrow_drop_up

Recommended Posts:



    Article Tags :

    Be the First to upvote.


    Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.