原理:(升序)
程序代码:
# 快排
def quick_sort(A, l, r):
if l < r:
pivot = A[l]
left = l
right = r
while left < right:
while A[right] > pivot and left < right:
right -= 1
# 左右不能相等,相等的话会进行移动,导致数组越界
if left < right:
A[left] = A[right]
left += 1
while A[left] <= pivot and left < right:
left += 1
if left < right:
A[right] = A[left]
right -= 1
A[left] = pivot
quick_sort(A, l, left-1)
quick_sort(A, left+1, r)
if __name__ == '__main__':
S = [0, 2, 1, 6]
quick_sort(S, 0, 3)
print(S)
原理(用数组表示完全二叉树的层序,最小堆):
程序代码:
# 堆排
def heap_sort(A):
for i in range((len(A) - 1) // 2, -1, -1):
while i < len(A):
# 子节点与父节点的位置关系
left, right = i * 2 + 1, i * 2 + 2
min_pos = i
if (left < len(A)) and (A[left] < A[min_pos]):
min_pos = left
if (right < len(A)) and (A[right] < A[min_pos]):
min_pos = right
# 如果最小值的位置改变了,需要考虑这个改变带来的影响
if min_pos != i:
A[i], A[min_pos] = A[min_pos], A[i]
i = min_pos
else:
break
if __name__ == '__main__':
S = [4, 3, 2, 1]
heap_sort(S)
print(S)
GOOD LUCK!