Professional Documents
Culture Documents
Bubble Sort Shell Script With and With Out Arrays
Bubble Sort Shell Script With and With Out Arrays
/bin/bash
# SCRIPT: bubblesort.sh
# LOGIC:
# Bubble sort is a simple sorting, it works by repeatedly
# stepping through the list to be sorted, comparing two items
# at a time and swapping them if they are in the wrong order.
# If you are sorting the data in Ascending order, at the end
# of the first pass, the "heaviest" element has move to
# bottom. In the second pass, the comparisons are made till
# the last but one position and now second largest element is
# placed at the last but one position. And so forth.
##############################################################
#
Define Functions Here
##############################################################
printnumbers()
{
echo ${ARRAY[*]}
#You can also use bellow code
#for ((i=0;i<count;i++))
#do
#echo -n " ${ARRAY[i]} "
#done
}
exchange()
{
temp=${ARRAY[$1]}
ARRAY[$1]=${ARRAY[$2]}
ARRAY[$2]=$temp
}
sortnumbers()
{
for (( last=count-1;last>0;last--))
do
for((i=0;i<last;i++))
do
j=$((i+1))
if [ ${ARRAY[i]} -gt ${ARRAY[j]} ]
then
exchange $i $j
fi
done
done
}
##############################################################
#
Variable Initialization
##############################################################
echo "Enter Numbers to be Sorted"
read -a ARRAY
count=${#ARRAY[@]}
##############################################################
#
Main Script Starts Here
##############################################################
echo "-------------------------------------------------------"
echo "Numbers Before Sort:"
printnumbers
echo
sortnumbers
echo "Numbers After Sort: "
printnumbers
echo "-------------------------------------------------------"
OUTPUT:
[root@www blog]# sh bubblesort.sh
Enter Numbers to be Sorted :
78 34 12 98 21 8 36 98 12 88 7 5 61 -12 62 -1 77 -46
-----------------------------------------------------Numbers Before Sort:
78 34 12 98 21 8 36 98 12 88 7 5 61 -12 62 -1 77 -46
Numbers After Sort:
-46 -12 -1 5 7 8 12 12 21 34 36 61 62 77 78 88 98 98
------------------------------------------------------
OUTPUT:
[root@www shell]# sh bubblesort2.sh
Enter Total Numbers to be Sorted : 6
Enter number 1: 12
Enter number 2: -4
Enter number 3: 6
Enter number 4: -11
Enter number 5: 43
Enter number 6: 9
Elements Before Sort
12 -4 6 -11 43 9
Elements After Sort:
-11 -4 6 9 12 43