python快速排序和堆排
# coding=utf-8 def quick_sort(arr, start, end): if start >= end: return left = start right = end pivotkey = arr[start] while left < right: while left < right and arr[right] >= pivotkey: right -= 1 arr[left] = arr[right] while left < right and arr[left] <= pivotkey: left += 1 arr[right] = arr[left] arr[left] = pivotkey quick_sort(arr, start, left-1) quick_sort(arr, right + 1, end) if __name__ == "__main__": test_list = [2, 10, 11, 6, 19, 21] quick_sort(test_list, 0, len(test_list)-1) print(test_list)
堆排序:
# coding=utf-8
import math
def print_tree(array):
"""
将列表打印成堆
:param array:
:return:
"""
index = 1
depth = math.ceil(math.log2(len(array))) # 因为补0了,不然应该是math.ceil(math.log2(len(array)+1))
sep = ' '
for i in range(depth):
offset = 2 ** i
print(sep * (2 ** (depth - i - 1) - 1), end='')
line = array[index:index + offset]
for j, x in enumerate(line):
print("{:>{}}".format(x, len(sep)), end='')
interval = 0 if i == 0 else 2 ** (depth - i) - 1
if j < len(line) - 1:
print(sep * interval, end='')
index += offset
print()
def heap_sort(arr):
def max_heapify(root_index, end_index):
# 减一因为堆的下标从1开始
max_child_index = root_index*2-1
# 有两个子节点的情况下, 比较两个子节点的大小
if max_child_index + 1 < end_index:
if arr[max_child_index+1] > arr[max_child_index]:
max_child_index += 1
# 将最大的子节点与根节点比较
if arr[max_child_index] > arr[root_index-1]:
arr[max_child_index], arr[root_index-1] = arr[root_index-1], arr[max_child_index]
for end_index in range(len(arr), 1, -1):
max_root_index = end_index // 2
for root_index in range(max_root_index, 0, -1):
max_heapify(root_index, end_index)
# 调换根节点和末节点
arr[0], arr[end_index-1] = arr[end_index-1], arr[0]
if __name__ == "__main__":
arr = [0, 74, 73, 59, 72, 64, 69, 43, 36, 70, 61, 4, 0, 16, 47, 67, 17, 31, 19, 24, 14, 20, 48, 5, 7, 3, 78, 84, 92, 97, 98]
print(arr)
print_tree(arr)
heap_sort(arr)
print("---------------" * 10)
print(arr)
print_tree(arr)