美文网首页
用数组编写几个shell程序

用数组编写几个shell程序

作者: jere觅 | 来源:发表于2015-11-22 22:26 被阅读0次

    数组倒序
    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<j; i++,j-- )); do
    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程序

          本文链接:https://www.haomeiwen.com/subject/ojkrhttx.html