Shell氣泡排序

weixin_48190880發表於2020-11-02

1、陣列值

#!/bin/bash
score=(1 10 66 20 11 88 6 19)
for ((i=1;i<${#score[*]};i++))
do
    for ((j=0;j<${#score[*]}-$i;j++))
    do
        if [ ${score[j]} -lt ${score[(($j+1))]} ]
        then temp=${score[j]}
             score[j]=${score[(($j+1))]}
             score[(($j+1))]=$temp
        fi
    done
done
echo ${score[*]}

2、鍵盤輸入陣列值

#!/bin/bash
k=0
while true
do
read –p “是否需要輸入數值?” do
    if [ $do == “no” ]
    then break
    fi
read –p  “請輸入第$(($k+1))個元素” key
    score[$k]=$key
    let k++
done

相關文章