1.冒泡排序:
#for((i=0;i<10;i++)) for i in {0..9} #两种方法都可以 do ((a[i]=$RANDOM % 1000)) #产生随机数 echo -n "${a[i]} " done function bubble() { len=${#a[@]} for((i=0;i<len;i++)) do for((j=i;j<len;j++)) do if [ ${a[i]} -ge ${a[j]} ] then tmp=${a[i]} ((a[i]=a[j])) ((a[j]=tmp)) fi done done } bubble echo echo "After bubble: " for((i=0;i<10;i++)) do echo -n "${a[i]} " done
运行结果:
2.求数组的最大子序列和:
#a=(-2 11 -4 13 -5 -2) function maxSum() #数组a是在后面定义 但是maxSum里面已经可用,可见a是全局的 { #local a="$*" #local len="$#" ((currSum=0)) ((mSum=0)) len=${#a[@]} for((i=1;i<len;i++)) do ((currSum=currSum+a[i])) #echo "a[i]: ${a[i]}" #echo "F: $currSum" if [ $currSum -gt $mSum ] then #echo "S: $currSum" ((mSum=currSum)) elif [ $currSum -lt "0" ] then ((currSum=0)) fi done return $mSum } a=(-2 11 -4 13 -5 -2) #maxSum "${a[@]}" maxSum echo $?
运行结果:
3. 二分查找:
binarySearch() { v=$1 #an="$1[@]" #a=${!an} a=${array[@]} #echo "len an ${#an[*]}" #echo "a ${#array[*]}" #echo an for i in $a do ar[i]=$i #echo $i done #echo "len $ar " low=1 high=${#ar[*]} (( times=0 )) while (( low <= high )) do (( ++times )) (( mid=(low+high)/2 )) #echo -n " mid="$mid #echo -n " ar[mid]="${ar[mid]} if (( v > ar[mid] )) then (( low = mid + 1 )) elif (( v < ar[mid] )) then (( high = mid - 1 )) else #echo -e "/nTimes="$times return $mid fi done #echo -e "/nTimes="$times echo "can not find" return -1 } for ((i=1;i<=100;++i)) do (( array[i] = i )) done binarySearch 2 echo -e "$?\ttimes" binarySearch 8 echo -e "$?\ttimes" binarySearch 101 echo -e "$?\ttimes" exit 0
运行结果:
不知道为什么不可以 return -1 ???
make it simple, make it happen
from: http://www.cnblogs.com/zhuyp1015/archive/2012/07/07/2580732.html