您的位置:首页 > 运维架构 > Shell

shell脚本实现冒泡排序(优化)

2018-01-09 00:00 417 查看
#!/bin/sh
#bubbling arithmetic
function bubbling(){
len=${#data[*]}
((len=len-1))
pos=0
for ((i=0;i<${#data[*]};i++))
do
flag="0" #using flag to end the foreach
# echo "${i} ${len}"
for ((j=0;j<${len};j++))
do
# echo "for to ij position ${flag} ${len}"
# echo "output data values ${data[$j]} ${data[$[j+1]]}"
if [ ${data[j]} -gt ${data[j+1]} ]
then
# echo "for to ${j} position ${flag} $[len-1]"
# data[0]=${data[$[j]]}
tmp=${data[j]} #swap array data
data[$j]=${data[j+1]}
data[$[j+1]]=${tmp}
pos=$j
flag="1"
fi
# echo "sort data are:${data[*]}"
done
len=${pos}
# echo "len and pos values are ${len} ${pos}"
if [ ${flag} -eq "0" ]
then
break
fi
done
echo ${data[*]}
#return 1
}
data=(1 5 6 9 2 6) #array data
bubbling ${data} #invoking method and by value
echo "${data[*]}" #return values

注:“$”符号表示引用变量,其中${data[$[j+1]]}和${data[${j+1}]}是不一样的,${data[$[j+1]]}表示先让j+1作运算并获取下标值,而${data[${j+1}]}仅表示获取j的下标值,关于+1它会自动忽视掉,若有更优化的算法,可以一块分享,探讨
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  ShellPage