2017-10-12 35 views
0
array=($(<abc.txt)) 
len=${#array[*]} 
i=0 
while [ $i -lt "$len" ] 
do 
j=0 
while [ $j -lt $(((len - 1)) - i)) ] 
do 
    k=$((j + 1)) 
    if [ "${array[$j]}" -gt "${array[$k]}" ] 
    then 
    temp=${array[$j]} 
    array[$j]=${array[$k]} 
    array[$k]=$temp 
    fi 
j=$k 
done 
i=$((i + 1)) 
done 
echo "${array[@]}" 

我的數組沒有排序,我也收到一條消息「:integer expression expected」。它可以在我朋友的電腦上正常工作。我只想從另一個文件輸入一個數組,然後使用bubblesort。如果我將數組聲明爲array =(1 2 3 4 9 8 7 6 5),它也可以正常工作。給定的bash腳本中的錯誤用於bubblesort的位置?

+0

任何你不使用'sort'命令的原因? –

+0

您不需要嵌套算術表達式; $(((len-1)-i))'就足夠了。 – chepner

+0

,因爲作爲學生我要實現bubblesort算法 –

回答

0

您的括號在第二條語句中不匹配,我更改了 len聲明。 chepner是正確的,shellcheck.net會爲你解決這個問題。 (你甚至可以在本地安裝shellcheck。)

#!/bin/bash 
#array=($(<abc.txt)) 
array=(1 2 3 4 9 8 7 6 5) 
len=${#array[@]} 
i=0 
while [ $i -lt "$len" ] 
do 
j=0 
while [ $j -lt "$(((len - 1) - i))" ] 
do 
    k=$((j + 1)) 
    if [ "${array[$j]}" -gt "${array[$k]}" ] 
    then 
    temp=${array[$j]} 
    array[$j]=${array[$k]} 
    array[$k]=$temp 
    fi 
j=$k 
done 
i=$((i + 1)) 
done 
echo "${array[@]}" 
+0

當我在數組中輸入數字時,我的文件正常工作,但是當我從文件中輸入數據時出現問題。如果我在輸入文件的最後一位數字後面沒有空格,則CR(\ r)會顯示最後一位數字。 –

+0

我已經嘗試了與CR和沒有,它仍然有效。在debian8 linux上測試bash 4.4.12確實echo -n「$ {array [@]}」解決你的問題? –

+0

對我來說,CR不允許排序。我使用Ubuntu 16.0.4,當我使用'set -vx'時,其中一行是'+'['9-gt $'5 \ r'']' :預期的整數表達式 '。 –