# Sorting an array in Bash using Bubble sort

• Difficulty Level : Easy
• Last Updated : 25 Nov, 2021

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 the 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```

Optimized Implementation:  The above function always runs O(n^2) time even if the array is sorted. It can be optimized by stopping the algorithm if the inner loop didn’t cause any swap.

```n=5
arr=(10 8 20 100 12)

echo "Original array is: \${arr[*]}";

flag=1;
for (( i = 0; i < \$n-1; i++ ))
do
flag=0;
for ((j = 0; j < \$n-1-\$i; j++ ))
do
if [[ \${arr[\$j]} -gt \${arr[\$j+1]} ]]
then
temp=\${arr[\$j]};
arr[\$j]=\${arr[\$j+1]};
arr[\$j+1]=\$temp;
flag=1;
fi
done

if [[ \$flag -eq 0 ]]; then
break;
fi```

Output:

```Original array is: 10 8 20 100 12
Final sorted Array is 8 10 12 20 100```

Worst and Average Case Time Complexity: O(n*n). The worst-case occurs when an array is reverse sorted.

Best Case Time Complexity: O(n). The best-case occurs when the array is already sorted.

Auxiliary Space: O(1)

Boundary Cases: Bubble sort takes minimum time (Order of n) when elements are already sorted.

Sorting In Place: Yes

Stable: Yes

My Personal Notes arrow_drop_up