• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
  • Skip to footer navigation

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • VCS
  • Interview Questions
  • Database
    • MariaDB
  • DevOps
    • Docker
    • Shell Scripting
  • Big Data
    • Hadoop
    • Cloudera
    • Hortonworks HDP

How to write Bubble sort in Bash

by admin

Bubble sort is a simple algorithm that basically bubbles up the elements of the array. This means that it traverses the array multiple times and swaps the adjacent elements if they are in the wrong order, as in the following diagram:

bubble sort in bash

Bubble sort Bash Script

Here is a simple bash script for bubble sort algorithm.

#!/bin/bash

echo "enter maximum number"
read n

# taking input from user
echo "enter Numbers in array:"
for (( i = 0; i < $n; i++ ))
do
    read nos[$i]
done

#printing the number before sorting
echo "Numbers in an array are:"
for (( i = 0; i < $n; i++ ))
do
    echo ${nos[$i]}
done

# Now do the Sorting of numbers
for (( i = 0; i < $n ; i++ ))
do
    for (( j = $i; j < $n; j++ ))
    do
        if [ ${nos[$i]} -gt ${nos[$j]}  ]; then
        t=${nos[$i]}
        nos[$i]=${nos[$j]}
        nos[$j]=$t
        fi
    done
done

# Printing the sorted number
echo -e "\nSorted Numbers "
for (( i=0; i < $n; i++ ))
do
    echo ${nos[$i]}
done

Sample Output from the above script:

$ bash bubblesort.sh
enter maximum number
6
enter Numbers in array:
2
4
7
8
22
3
Numbers in an array are:
2
4
7
8
22
3

Sorted Numbers
2
3
4
7
8
22

Filed Under: DevOps, Shell Scripting

Some more articles you might also be interested in …

  1. How to Find and Delete Empty Directories and Files in Linux
  2. ansible-playbook – Execute tasks defined in playbook on remote machines over SSH
  3. “docker machine” Command Examples
  4. ansible-inventory – Display or dump an Ansible inventory (Command Examples)
  5. How to install docker on CentOS / RHEL / Fedora
  6. How to convert text files to all upper or lower case
  7. “docker secrete” Command Examples
  8. Unable to run NGINX Docker due to “13: Permission denied”
  9. How to use shell expansions for generating shell tokens under Linux
  10. How to Trace Python Scripts using trace.py

You May Also Like

Primary Sidebar

Recent Posts

  • Vanilla OS 2 Released: A New Era for Linux Enthusiasts
  • mk Command Examples
  • mixxx Command Examples
  • mix Command Examples

© 2025 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright