写一个冒泡排序的Python代码
时间: 2024-05-07 16:23:58 浏览: 13
好的,这是一个简单的冒泡排序的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
```
你可以将你想要排序的数组传递给这个函数,它会返回一个已排序的数组。
相关问题
写一个冒泡排序Python代码
当然可以,以下是冒泡排序的Python代码实现:
```python
def bubbleSort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1] :
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
# 测试
arr = [64, 34, 25, 12, 22, 11, 90]
sorted_arr = bubbleSort(arr)
print("排序后的数组:")
for i in range(len(sorted_arr)):
print("%d" %sorted_arr[i])
```
用面向对象的方式写一个冒泡排序 python代码
class BubbleSort:
def __init__(self, nums):
self.nums = nums
def sort(self):
n = len(self.nums)
for i in range(n):
for j in range(0, n-i-1):
if self.nums[j] > self.nums[j+1] :
self.nums[j], self.nums[j+1] = self.nums[j+1], self.nums[j]
nums = [64, 34, 25, 12, 22, 11, 90]
bubbleSort = BubbleSort(nums)
bubbleSort.sort()
print ("排序后的数组:")
for i in range(len(nums)):
print(nums[i], end=" ")
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![py](https://img-home.csdnimg.cn/images/20210720083646.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)