python冒泡排序法完整代码
时间: 2024-01-22 09:16:40 浏览: 29
以下是Python冒泡排序算法的完整代码:
```python
def bubbleSort(nums):
flag = True
for i in range(len(nums) - 1):
for j in range(len(nums) - 1 - i):
if nums[j] > nums[j + 1]:
nums[j], nums[j + 1] = nums[j + 1], nums[j]
flag = False
if flag:
break
return nums
arr = [1, 2697, 300, 40, -5, 6]
print(bubbleSort(arr)) # 输出:[-5, 1, 6, 40, 300, 2697]
```
相关问题
Python冒泡排序算法代码例子
当然,以下是Python实现冒泡排序算法的代码例子:
```python
def bubble_sort(arr):
n = len(arr)
# 遍历所有数组元素
for i in range(n):
# Last i elements are already sorted
for j in range(0, n-i-1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater than the next element
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
```
这段代码中,我们首先定义了一个`bubble_sort`函数来实现冒泡排序。排序的主循环通过遍历数组来进行。内部循环是在数组中遍历当前未排序的元素,如果发现前一个元素比后一个元素大,那么就交换它们的位置。这样,每次内部循环都可以将最大的元素移动到数组的末尾。
python实现冒泡法排序完整代码
当然,我可以帮你提供Python实现冒泡排序的完整代码。以下是示例代码:
```
def bubbleSort(arr):
n = len(arr)
# 遍历所有数组元素
for i in range(n):
# Last i elements are already sorted
for j in range(n - i - 1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
# than the next element
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
# 测试
arr = [64, 34, 25, 12, 22, 11, 90]
bubbleSort(arr)
print("排序后的数组:")
for i in range(len(arr)):
print("%d" % arr[i]),
```
这是一种经典的冒泡排序算法实现,可以实现将一个数组从小到大进行排序。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)