Python 冒泡排序代码示例及时间复杂度分析
这是冒泡排序的 Python 代码示例:
def bubble_sort(arr):
n = len(arr)
for i in range(n):
# Last i elements are already sorted
for j in range(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]
return arr
该算法的时间复杂度为 O(n^2),因为它需要执行 n 次外部循环和 n 次内部循环。在最坏情况下,即数组已经按相反顺序排列,它需要执行 n(n-1)/2 次比较和交换操作。
原文地址: https://www.cveoy.top/t/topic/oG91 著作权归作者所有。请勿转载和采集!