Thursday, July 29, 2010

Selection Sort Shell Script


#!/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.

9 comments:

  1. Thank you very much. I found the script here only.
    Thanks for your effort. keep going....

    ReplyDelete
  2. The logic that you share in this article is wonderful and I need this help. I try too many blogs to find about paper writing service and this information but I never get it but at last I able to get this information. You work so brilliantly in this article and I love it.

    ReplyDelete
  3. Very nice post. Interesting news.

    ReplyDelete

  4. By nature, the check changing framework is intended to make saving money exchanges less demanding contrasted with the customary framework. Through check changing frameworks, the troubles of customary keeping money exchanges can be tended to with no issue by any stretch of the imagination. Check Cashing chicago

    ReplyDelete