这是我对n个数字进行冒泡排序的代码:
#!/bin/bash
echo -n "Input n, the number of numbers"
read N
declare -a array[N]
echo -e "Input the elements, press enter after each element"
for i in seq 1 $N
do
read array[$i]
done
swap1()
{ # for swapping two numbers, we are employing bubble sort
local temp = ${array[$1]}
array[$1] = ${array[$2]}
array[$2]=$temp
return
}
numb_elements=${#array[@]}
let "comparisons = $numb_elements - 1"
count=1
while [ "$comparisons" -gt 0]
do
index =0
while[ "$index" -lt "$comparisons" ];do
if [ ${array[$index]} \> ${array[ 'expr $index + 1']} ]
then
swap1 $index 'expr $index + 1'
fi
let "index += 1" # Or, index+=1 on Bash, ver. 2.1 or newer
done
let "comparisons -=1"
echo
echo "$count: ${array[@]}
echo
let "count +=1"
done
exit 0
我对此代码有两个问题:
我尝试了while [] ; do
,但它没有用。
我刚刚尝试使用bash语法。
答案 0 :(得分:2)
此外不写
for i in seq 1 $N
在集合{“seq”,“1”,$ N}上迭代i,但输入
for i in $(seq 1 $N)
将命令的结果作为代码的一部分插入。
你忘记了这一行中的结束语:
echo "$count: ${array[@]}
嵌套循环的代码也是非常缩进的,所以它有点难以阅读和调试。
答案 1 :(得分:2)
到目前为止,我发现了以下错误:
while [ "$comparisons" -gt 0 ]
^ missing space here
while [ "$index" -lt "$comparisons" ];do
^ missing space
echo "$count: ${array[@]}"
^ missing quote
请注意,在bash中[
相当于test
命令,因此[
和]
周围需要一个空格,与许多其他编程语言不同。
答案 2 :(得分:1)
试试这个:
while [ "$comparisons" -gt 0]
应该是(在结束括号]
之前注意空格):
while [ "$comparisons" -gt 0 ]
答案 3 :(得分:1)
你犯了一系列错误:
这是您的代码更正。
#!/bin/bash
swap1() { # for swapping two numbers, we are employing bubble sort
local temp=${array[$1]}
array[$1]=${array[$2]}
array[$2]=$temp
return
}
echo -n "Input n, the number of numbers: "
read N
declare -a array[$N]
echo -e "Input the elements, press enter after each element"
for i in `seq 1 $N`
do
read array[$i]
done
numb_elements=${#array[@]}
#let "comparisons = $numb_elements - 1"
comparisons=$numb_elements
count=1
while [ "$comparisons" -gt 0 ]
do
index=1
while [ "$index" -lt "$comparisons" ]
do
tmp=`expr $index + 1`
if [ ${array[$index]} -gt ${array[$tmp]} ]
then
swap1 $index $tmp
fi
let "index += 1" # Or, index+=1 on Bash, ver. 2.1 or newer
done
let "comparisons -= 1"
echo
echo "$count: ${array[@]}"
echo
let "count += 1"
done
exit 0