[英]Bubble sort in Linux/Unix shell scripting
I am trying to perform bubble sort is Unix shell script.我正在尝试执行冒泡排序是 Unix shell 脚本。 Why is my code not working?
为什么我的代码不起作用?
a=(10 8 20 25 12)
for ((i=0;i<5;i++))
do
for((j=0;j<5;j++))
do
if ((${a[j]} > ${a[$((j+1))]}))
then
v=${a[$j]}
a[$j]=${a[$((j+1))]}
a[$((j+1))]=$v
fi
done
done
echo ${a[*]}
echo "end..."
I guess this is homework. 我想这是功课。 therefore I don't give codes, just point out the errors in your codes:
因此,我不提供代码,只需指出代码中的错误:
for((j=0;j<5;j++))
then read a[j+1]
, here would be problem because when j=4
, j+1
doesn't exist for((j=0;j<5;j++))
然后读a[j+1]
,这里会有问题,因为当j=4
, j+1
不存在
fix that, your program will sort. 修复它,你的程序将排序。
Try this:尝试这个:
echo "Enter size of array";
read n; #get the size of array from user.
echo "Enter the array";
read -a arr; #get the array form user eg: 2 3 4 5 6
echo "Orignal array is: ${arr[*]}"; #print orignal array
flag=1;
for (( i = 0; i < $n-1; i++ ))
do
flag=0;
for ((j = 0; j < $n-1-$i; j++ ))
do
if [[ ${arr[$j]} -gt ${arr[$j+1]} ]]
then
temp=${arr[$j]};
arr[$j]=${arr[$j+1]};
arr[$j+1]=$temp;
flag=1;
fi
done
if [[ $flag -eq 0 ]]; then
break;
fi
done
echo "Final sorted Array is ${arr[*]}";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.