在linux上使用shell脚本编写冒泡排序
时间: 2024-05-09 19:15:43 浏览: 83
以下是在Linux上使用shell脚本编写冒泡排序的示例:
```shell
#!/bin/bash
# 定义数组
arr=(5 2 9 1 5 6)
# 计算数组长度
len=${#arr[@]}
# 冒泡排序
for (( i=0; i<$len-1; i++ ))
do
for (( j=0; j<$len-i-1; j++ ))
do
if (( ${arr[j]} > ${arr[j+1]} ))
then
# 交换元素位置
temp=${arr[j]}
arr[j]=${arr[j+1]}
arr[j+1]=$temp
fi
done
done
# 输出排序后的数组
echo ${arr[@]}
```
解释一下:
首先定义了一个数组 `arr`,然后计算数组长度 `len`。
接下来进行冒泡排序,外层循环控制排序轮数,内层循环控制每轮比较次数。如果相邻的元素大小关系不正确,则交换它们的位置。
最后输出排序后的数组。
阅读全文
相关推荐
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)
![-](https://img-home.csdnimg.cn/images/20241226111658.png)