#!/bin/bash#!/bin/bash
# SCRIPT: selectionsort.sh
#
# LOGIC : Here, to sort the data in ascending order, the first element
# ARRAY[0] is compared with all the other elements till the end of the
# array. If it is greater than any other the elements then they are
# interchanged. So after the first iteration of the outer for loop
# smallest element will be placed at the first position. The same pro-
# cedure is repeated for the other elements too.
#
#####################################################################
# Define Functions Here #
#####################################################################
printnumbers()
{
echo ${ARRAY[*]}
}
swap()
{
temp=${ARRAY[$1]}
ARRAY[$1]=${ARRAY[$2]}
ARRAY[$2]=$temp
}
sortnumbers()
{
for ((i=0;i<count;i++))
do
min=$i
for ((j=i+1;j<count;j++))
do
if [ ${ARRAY[j]} -lt ${ARRAY[min]} ]
then
min=$j
fi
done
swap $i $min
done
}
#####################################################################
# Variable Initialization #
#####################################################################
echo "Enter Numbers to be Sorted : "
read -a ARRAY
count=${#ARRAY[@]}
#####################################################################
# Main Script Starts Here #
#####################################################################
echo "---------------------------------------------------------------"
echo "Numbers Before Sort:"
printnumbers
sortnumbers
echo "Numbers After Sort: "
printnumbers
echo "---------------------------------------------------------------"
OUTPUT:
[root@www blog]# sh selectionsort.sh
Enter Numbers to be Sorted :
34 76 -8 12 23 5 9 -2 88 41 62
---------------------------------------------------------------
Numbers Before Sort:
34 76 -8 12 23 5 9 -2 88 41 62
Numbers After Sort:
-8 -2 5 9 12 23 34 41 62 76 88
---------------------------------------------------------------
NOTE: If we complement the if condition in this program, it will give
out the sorted array in descending order.
Thursday, July 29, 2010
Selection Sort Shell Script
Labels:
Shell Scripts
Subscribe to:
Post Comments (Atom)
Thank you very much. I found the script here only.
ReplyDeleteThanks for your effort. keep going....