📜  用于堆排序的时间复杂度图的Python代码

📅  最后修改于: 2021-05-05 01:23:37             🧑  作者: Mango

先决条件:HeapSort
堆排序是基于二进制堆数据结构的基于比较的排序技术。这与选择排序类似,在该排序中,我们首先找到最大元素,然后将最大元素放在最后。我们对剩余元素重复相同的过程。

我们在这里实现堆排序,将其称为不同大小的随机列表,测量不同大小所花费的时间,并生成输入大小与所花费时间的关系图。

# Python Code for Implementation and running time Algorithm 
# Complexity plot of Heap Sort 
# by Ashok Kajal 
# This python code intends to implement Heap Sort Algorithm
# Plots its time Complexity on list of different sizes
  
# ---------------------Important Note -------------------
# numpy, time and matplotlib.pyplot are required to run this code 
import time
from numpy.random import seed
from numpy.random import randint
import matplotlib.pyplot as plt
  
  
# find left child of node i
def left(i):
    return 2 * i + 1
  
# find right child of node i
def right(i):
    return 2 * i + 2
  
# calculate and return array size
def heapSize(A):
    return len(A)-1
  
  
# This function takes an array and Heapyfies
# the at node i
def MaxHeapify(A, i):
    # print("in heapy", i)
    l = left(i)
    r = right(i)
      
    # heapSize = len(A)
    # print("left", l, "Rightt", r, "Size", heapSize)
    if l<= heapSize(A) and A[l] > A[i] :
        largest = l
    else:
        largest = i
    if r<= heapSize(A) and A[r] > A[largest]:
        largest = r
    if largest != i:
       # print("Largest", largest)
        A[i], A[largest]= A[largest], A[i]
       # print("List", A)
        MaxHeapify(A, largest)
      
# this function makes a heapified array
def BuildMaxHeap(A):
    for i in range(int(heapSize(A)/2)-1, -1, -1):
        MaxHeapify(A, i)
          
# Sorting is done using heap of array
def HeapSort(A):
    BuildMaxHeap(A)
    B = list()
    heapSize1 = heapSize(A)
    for i in range(heapSize(A), 0, -1):
        A[0], A[i]= A[i], A[0] 
        B.append(A[heapSize1])
        A = A[:-1]
        heapSize1 = heapSize1-1
        MaxHeapify(A, 0)
          
  
# randomly generates list of different
# sizes and call HeapSort funtion
elements = list()
times = list()
for i in range(1, 10):
  
    # generate some integers
    a = randint(0, 1000 * i, 1000 * i)
    # print(i)
    start = time.clock()
    HeapSort(a)
    end = time.clock()
  
    # print("Sorted list is ", a)
    print(len(a), "Elements Sorted by HeapSort in ", end-start)
    elements.append(len(a))
    times.append(end-start)
  
plt.xlabel('List Length')
plt.ylabel('Time Complexity')
plt.plot(elements, times, label ='Heap Sort')
plt.grid()
plt.legend()
plt.show()
# This code is contributed by Ashok Kajal

输出 :

输入:随机生成不同大小的未排序列表输出:1000个元素按0.023797415087301488中的HeapSort排序2000个元素按0.053856713614550245245个HeapSort排序3000个元素按0.08474737185133563 4000个元素按HeapSort排序0.13578669978414837 5000个元素按HeapSort排序6000个元素按6000个排序由HeapSort在0.1875901601906662中进行排序7000个元素按HeapSort在0.21982946862249264中进行排序8000个元素按HeapSort在0.2724293921580738中进行排序9000个元素按HeapSort在0.30996323029421546中进行排序