用python写一个冒泡排序程序
时间: 2023-05-29 12:02:46 浏览: 47
以下是用 Python 编写的冒泡排序程序。
```
def bubble_sort(array):
n = len(array)
for i in range(n):
for j in range(0, n-i-1):
if array[j] > array[j+1]:
array[j], array[j+1] = array[j+1], array[j]
return array
```
在此程序中,`array` 是要排序的数组。在第一层循环中,我们遍历整个数组。在第二层循环中,我们比较相邻的元素并交换它们的位置,以便让更小的元素移动到数组的左侧。通过这种方式,每次循环都可以将最大的元素向数组的右侧移动,直到所有元素都有序排列。最后,我们返回排好序的数组。
相关问题
使用python写一个冒泡排序程序
以下是Python实现冒泡排序的示例代码:
```python
def bubble_sort(arr):
n = len(arr)
# 遍历所有数组元素
for i in range(n):
# 最后i个元素已经排好序了
for j in range(0, n-i-1):
# 如果当前元素大于下一个元素,则交换它们
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# 示例
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("排序后的数组:")
for i in range(len(arr)):
print("%d" %arr[i]),
```
输出:
```
排序后的数组:
11
12
22
25
34
64
90
```
用python写一个冒泡排序的程序
好的,下面是Python实现的冒泡排序代码:
```python
def bubble_sort(arr):
n = len(arr)
# 遍历所有数组元素
for i in range(n):
# 最后 i 个元素已经排好序,不需要再比较
for j in range(0, n-i-1):
# 如果当前元素大于下一个元素,则交换它们的位置
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
# 示例
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("排序后的数组:")
for i in range(len(arr)):
print("%d" % arr[i])
```
以上代码中,`bubble_sort` 函数接受一个数组作为参数,然后使用两层循环遍历所有数组元素,通过比较相邻元素的大小来进行排序。最后输出排序后的数组。
相关推荐
![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)