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

#!/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它会自动忽视掉,若有更优化的算法,可以一块分享,探讨

猜你喜欢

转载自my.oschina.net/u/3378039/blog/1604494