bash编程实现冒泡排序

来源:互联网 发布:论坛软件群发 编辑:程序博客网 时间:2024/06/07 07:44

冒泡排序是比较相邻两位数大小,将大(或者小)的数字放在后面,再不断重复上述步骤获得数字排序的方法,网上有很多不同语言的实现方法,用bash的比较少,下面是我参考百度百科C语言版用bash脚本写的程序。

#! /bin/bash
#冒泡排序
declare -i n
declare -i i
read -p "enter num: " -a num
n=${#num[@]}
while [ $n -gt 1 ]
do
    i=1
    while [ $i -lt $n ]
    do
        if [ ${num[$i-1]} -gt ${num[$i]} ]
        then
            tm=${num[$i]}
            num[$i]=${num[$i-1]}
            num[$i-1]=$tm
        fi
        i=$i+1
    done
    echo "           ${num[@]}"
    n=$n-1
done

在ubuntu15.04下的测试结果
5 4 3 2 1
4 3 2 1 5
3 2 1 4 5
2 1 3 4 5
1 2 3 4 5

0 0
原创粉丝点击