数组练习

1.输入若干个数值存入数组中,采用冒泡算法进行升序或降序排序
#!/bin/bash
declare -a number
for (( i=0; i<20; i++ ));do
  number[$i]=$RANDOM
done
echo "before sort:"
echo ${number[@]}

declare -i n=20
for (( i=0; i<n-1; i++ ));do
  for (( j=0; j<n-1-i; j++ ));do
    let next=$j+1
    if (( ${number[$j]} < ${number[$next]} ));then
      tmp=${number[$next]}
      number[$next]=${number[$j]}
      number[$j]=$tmp
    fi
  done
done
echo "after sort:"
echo ${number[*]}
echo "the max integer is ${number[0]},the min integer is ${number[$(( n-1 ))]}"
2.将下图所示,实现转置矩阵

数组练习_第1张图片

#!/bin/bash
declare -i n=3
declare -A matrix
print(){
for (( i=0; i<n; i++ ));do
  for (( j=0; j<n; j++ ));do
    echo -e "${matrix[$i$j]}\t\c"
  done
  echo
done
}

for (( i=0; i<n; i++ ));do
  for (( j=0; j<n; j++ ));do
    matrix[$i$j]=$(( j+i*n+1 ))
  done
done
echo "the original matrix as below:"
print
for (( i=0; i<n; i++ ));do
  for (( j=0; j<n; j++ ));do
    if (( i<j ));then
      tmp=${matrix[$i$j]}
      matrix[$i$j]=${matrix[$j$i]}
      matrix[$j$i]=$tmp
    fi
  done
done
echo "the transformed matrix as below:"
print
unset n
unset matrix
unset i
unset j
unset print

你可能感兴趣的:(练习,练习)