• 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. What is the purpose of .bash_profile file under User Home Directory In Linux
  2. Kubernetes Command Line Reference (Cheatsheet)
  3. How To Change The Time Zone For A Docker Container
  4. Set up Jupyter Notebook in VS Code for Data Science
  5. How to Configure Network Namespaces in Docker Containers
  6. Examples of creating command alias in different shells
  7. ValueError: Masked arrays must be 1-D
  8. How to convert text files to all upper or lower case
  9. How to Build and push Docker Image to the Docker Hub Repository
  10. Puppet Server’s Resources Cheat Sheet with Examples

You May Also Like

Primary Sidebar

Recent Posts

  • grpck command – Remove corrupt or duplicate entries in the /etc/group and /etc/gshadow files.
  • xxd command – Expressed in hexadecimal form
  • sesearch: command not found
  • macof: command not found

© 2022 · The Geek Diary

  • Archives
  • Contact Us
  • Copyright