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

The Geek Diary

  • OS
    • Linux
    • CentOS/RHEL
    • Solaris
    • Oracle Linux
    • VCS
  • Interview Questions
  • Database
    • oracle
    • oracle 12c
    • ASM
    • mysql
    • 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 check the status and space used by images and containers
  2. Beginners Guide to The Docker World
  3. Backtick (`) symbol in Linux Shell Scripting
  4. How to Use External Python modules in MySQL Shell
  5. ansible-playbook: command not found
  6. How to Pause and Resume Docker Containers
  7. How to Write Ansible Playbook and run it using the ansible-playbook command
  8. kubectl: command not found
  9. Docker Troubleshooting – “conflict: unable to delete, image is being used by running container”
  10. Endpoint is not Created for Service in Kubernetes

You May Also Like

Primary Sidebar

Recent Posts

  • powertop Command Examples in Linux
  • powertop: command not found
  • powerstat: command not found
  • powerstat Command Examples in Linux

© 2023 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright