用数组编写几个shell程序

数组倒序
1.test 'array reverse'
echo "input seven number to form an array";
for (( i=0; i<7; i++ )); do
read a;
yes[i]=$a;
done;
echo "Original array: ${yes[@]}";
for (( i=0,j=6; i t=${yes[i]};
yes[i]=${yes[j]};
yes[j]=$t;
done;
echo "Sorted array: ${yes[@]}";

命令执行如下:
jeremy@ubuntu:~$ chmod 755 /tmp/reverse
jeremy@ubuntu:~$ /tmp/reverse
input seven number to form an array
4
5
1
2
3
7
6
Original array: 4 5 1 2 3 7 6
Sorted array: 6 7 3 2 1 5 4

冒泡排序法:
2.test 'BubbleSort'
echo "input seven number to form an array";

for (( i=0; i<7; i++ )); do
read a;
yes[i]=$a;
done;
echo "Original array: ${yes[@]}";

for (( i=0; i<7; i++ )); do

for (( j=0; j<6-i; j++ )); do
if (( ${yes[j]} > ${yes[j+1]} )); then
t=${yes[j]};
yes[j]=${yes[j+1]};
yes[j+1]=$t;
fi
done;

done;
echo "Sorted array: ${yes[@]}";

命令执行如下:
jeremy@ubuntu:~$ chmod 755 /tmp/BubbleSort
jeremy@ubuntu:~$ /tmp/BubbleSort
input seven number to form an array
4
5
1
2
3
7
6
Original array: 4 5 1 2 3 7 6
Sorted array: 1 2 3 4 5 6 7

你可能感兴趣的:(用数组编写几个shell程序)