Sorting an array in Bash using Bubble sort

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


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 .

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 .





# 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++))
    for((j = i; j<5-i-1; j++))
        if ((${arr[j]} > ${arr[$((j+1))]}))
            # swap
            temp = ${arr[$j]}
            arr[$j] = ${arr[$((j+1))]}  
            arr[$((j+1))] = $temp
echo "Array in sorted order :"
echo ${arr[*]}


Output :

Array in sorted order :
8 10 12 20 100

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at to report any issue with the above content.