用shell写一个冒泡排序
时间: 2024-05-21 21:10:52 浏览: 9
#!/bin/bash
# Bubble sort in shell script
# Define the array of numbers to be sorted
numbers=(5 2 8 4 9)
# Get the length of the array
length=${#numbers[@]}
# Outer loop to iterate through all the elements of the array
for ((i=0;i<$length;i++));
do
# Inner loop to compare adjacent elements and swap them if necessary
for ((j=0;j<$length-i-1;j++));
do
# Compare adjacent elements
if [ ${numbers[j]} -gt ${numbers[$((j+1))]} ]; then
# Swap the elements
temp=${numbers[j]}
numbers[j]=${numbers[$((j+1))]}
numbers[$((j+1))]=$temp
fi
done
done
# Print the sorted array
echo "Sorted array: ${numbers[@]}"
相关问题
用shell写个冒泡排序算法
可以的,以下是一个用shell写的冒泡排序算法:
#!/bin/bash
arr=(5 3 8 4 2)
len=${#arr[@]}
for ((i=; i<$len-1; i++))
do
for ((j=; j<$len-i-1; j++))
do
if [ ${arr[j]} -gt ${arr[$((j+1))]} ]
then
temp=${arr[j]}
arr[j]=${arr[$((j+1))]}
arr[$((j+1))]=$temp
fi
done
done
echo ${arr[@]}
这个脚本定义了一个数组arr,然后使用两个循环来实现冒泡排序。第一个循环控制排序的轮数,第二个循环控制每一轮中比较的次数。在比较过程中,如果前一个元素大于后一个元素,就交换它们的位置。最后输出排序后的数组。
用shell脚本写一个冒泡程序
A:
```
#!/bin/bash
# 定义一个测试数组
arr=(8 3 1 7 0 4 6 9 2 5)
# 冒泡排序函数
function bubble_sort() {
for (( i = 0; i < ${#arr[@]}-1; i++ )); do
for (( j = 0; j < ${#arr[@]}-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
}
# 调用冒泡排序函数
bubble_sort
# 打印排序后的数组
echo "排序后的数组为:${arr[@]}"
```
以上是一个用shell脚本写的冒泡排序程序,可以对任意数组进行排序,然后输出排序后的数组。程序中定义了一个测试数组,然后调用冒泡排序函数进行排序,并输出排序后的结果。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)