编写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]
# Example usage
arr = [64, 34, 25, 12, 22, 11, 90]
bubble_sort(arr)
print("Sorted array is:")
for i in range(len(arr)):
print("%d" %arr[i]),
该程序首先定义了一个函数bubble_sort,它接受一个列表作为输入参数。然后程序计算列表的长度,并使用两个嵌套的循环来遍历列表并交换元素,直到列表被排序。最后,程序打印出排序后的列表
原文地址: https://www.cveoy.top/t/topic/hq2s 著作权归作者所有。请勿转载和采集!