Skip to content
Related Articles

Related Articles

Sorting an array in Bash using Bubble sort
  • Difficulty Level : Medium
  • Last Updated : 22 Apr, 2020

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 .




# 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 = 0; j<5-i-1; j++))
    do
      
        if [ ${arr[j]} -gt ${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[*]}


Output :

Array in sorted order :
8 10 12 20 100
My Personal Notes arrow_drop_up
Recommended Articles
Page :