bash 函数思想实现数组冒泡排序
1 #!/bin/env sh
2
3 read -p 'input length of array:' var
4 [[ ! $var =~ [[:digit:]] ]] && echo 'input wrong' && exit 5
5
6 declare -a pp
7
8 for z in `seq 0 1 $[var-1]`;do
9 pp[$z]=$RANDOM
10 done
11
12 echo ${pp[@]}
13
14 function desc(){
15 local pp
16 declare -a pp
17 pp=($@)
18 local num=${#pp[*]}
19 echo $num
20 for ((i=0;i<num;i++));do
21 for ((j=i+1;j<num;j++));do
22 if [ ${pp[i]} -lt ${pp[j]} ];then
23 nn=${pp[i]}
24 pp[i]=${pp[j]}
25 pp[j]=$nn
26 fi
27 done
28 done
29 echo "desc sort:"
30 echo ${pp[*]}
31 }
32
33 desc ${pp[*]}
34
35 function asc(){
36 local pp
37 declare -a pp
38 pp=($*)
39 local num=${#pp[*]}
40 echo $num
41 for ((i=0;i<num;i++));do
42 for ((j=i+1;j<num;j++));do
43 if [ ${pp[i]} -gt ${pp[j]} ];then
44 nn=${pp[i]}
45 pp[i]=${pp[j]}
46 pp[j]=$nn
47 fi
48 done
49 done
50
51 echo "asc scort:"
52 echo ${pp[@]}
53 }
54
55 asc ${pp[*]}
bash 中不能直接传递数组,只能先拆包在重新生成数组
开始先利用[[ ]]做正则条件判断,非数字退出