📅  最后修改于: 2023-12-03 15:37:49.631000             🧑  作者: Mango
堆排序是一种高效的排序算法,它的时间复杂度为O(nlogn)。下面是堆排序时间复杂度图的Python代码。
import matplotlib.pyplot as plt
def heap_sort_time_complexity(n):
arr = list(range(n))
plt.figure()
plt.xlabel('n (array size)')
plt.ylabel('time complexity (operations)')
plt.title('Heap Sort Time Complexity')
for i in range(1, n + 1):
arr = list(range(i))
heap_sort(arr)
plt.scatter(i, heap_sort.counter, color='r')
heap_sort.counter = 0
plt.show()
def heapify(arr, n, i):
largest = i
l = 2 * i + 1
r = 2 * i + 2
if l < n and arr[i] < arr[l]:
largest = l
if r < n and arr[largest] < arr[r]:
largest = r
if largest != i:
arr[i], arr[largest] = arr[largest], arr[i]
heapify(arr, n, largest)
def heap_sort(arr):
heap_sort.counter = 0
n = len(arr)
for i in range(n // 2 - 1, -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)
heap_sort.counter += 1
heap_sort_time_complexity(1000)
代码分为两部分,heap_sort
和heap_sort_time_complexity
。
heap_sort
是一个标准的堆排序算法,使用了一个计数器来计算排序操作的数量。
heap_sort_time_complexity
用来生成堆排序时间复杂度图。它从1到n改变数组的大小,然后使用heap_sort
来对数组进行排序,并记录下操作的数量。最后,将数组大小和操作数量的散点图绘制出来。
运行上述代码,得到的结果如下图:
可以看到,堆排序的时间复杂度是O(nlogn)。这个结果和我们预期的结果是一致的。