# 冒泡排序
def bubble_sort(arr):
for i in range(0, len(arr)):
for j in range(0, len(arr)-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
# 选择排序
def selection_sort(arr):
for i in range(0, len(arr)):
for j in range(i+1, len(arr)):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
# 插入排序
def insert_sort(arr):
for i in range(1,len(arr)):
for j in range(0,i):
if arr[j] > arr[i]:
arr[j], arr[i] = arr[i], arr[j]
return arr
# 快速排序
def quick_sort(arr):
"""快速排序"""
if len(arr) < 2:
return arr
# 选取基准,随便选哪个都可以,选中间的便于理解
mid = arr[len(arr) // 2]
# 定义基准值左右两个数列
left, right = [], []
# 从原始数组中移除基准值
arr.remove(mid)
for item in arr:
# 大于基准值放右边
if item >= mid:
right.append(item)
else:
# 小于基准值放左边
left.append(item)
# 使用迭代进行比较
return quick_sort(left) + [mid] + quick_sort(right)
# 归并排序
def merge_sort(arr):
if len(arr)<2:
return arr
mid = len(arr)//2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left,right)
def merge(left,right):
result = []
while len(left)>0 and len(right)>0:
if left[0]<=right[0]:
result.append(left.pop(0))
else:
result.append(right.pop(0))
result += left
result += right
return result
def heapify(arr, n, i):
largest = i
left = 2 * i + 1
right = 2 * i + 2
if left < n and arr[i] < arr[left]:
largest = left
if right < n and arr[largest] < arr[right]:
largest = right
if largest != i:
arr[i],arr[largest] = arr[largest],arr[i] # 交换
heapify(arr, n, largest)
def heap_sort(arr):
n = len(arr)
# Build a maxheap.
for i in range(n, -1, -1):
heapify(arr, n, i)
# 一个个交换元素
for i in range(n-1, 0, -1):
arr[i], arr[0] = arr[0], arr[i] # 交换
heapify(arr, i, 0)
if __name__ == '__main__':
arr = [3,2,6,12,1,7,5,11,9,8,10,4]
print('冒泡排序:',bubble_sort(arr))
arr = [3,2,6,12,1,7,5,11,9,8,10,4]
print('选择排序:',selection_sort(arr))
arr = [3,2,6,12,1,7,5,11,9,8,10,4]
print('插入排序:',insert_sort(arr))
arr = [3,2,6,12,1,7,5,11,9,8,10,4]
print('快速排序:',quick_sort(arr))
arr = [3,2,6,12,1,7,5,11,9,8,10,4]
print('归并排序:',merge_sort(arr))
arr = [3,2,6,12,1,7,5,11,9,8,10,4]
print('堆排序: ',merge_sort(arr))
python 排序算法
最新推荐文章于 2023-05-25 16:00:00 发布