Prerequisite : HeapSort
Heap sort is a comparison based sorting technique based on Binary Heap data structure. It is similar to selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for remaining element.
We implement Heap Sort here, call it for different sized random lists, measure time taken for different sizes and generate a plot of input size vs time taken.
Python
import time
from numpy.random import seed
from numpy.random import randint
import matplotlib.pyplot as plt
def left(i):
return 2 * i + 1
def right(i):
return 2 * i + 2
def heapSize(A):
return len (A) - 1
def MaxHeapify(A, i):
l = left(i)
r = right(i)
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:
A[i], A[largest] = A[largest], A[i]
MaxHeapify(A, largest)
def BuildMaxHeap(A):
for i in range ( int (heapSize(A) / 2 ) - 1 , - 1 , - 1 ):
MaxHeapify(A, i)
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 )
elements = list ()
times = list ()
for i in range ( 1 , 10 ):
a = randint( 0 , 1000 * i, 1000 * i)
start = time.clock()
HeapSort(a)
end = time.clock()
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()
|
Output :
Input : Unsorted Lists of Different sizes are Generated Randomly
Output :
1000 Elements Sorted by HeapSort in 0.023797415087301488
2000 Elements Sorted by HeapSort in 0.053856713614550245
3000 Elements Sorted by HeapSort in 0.08474737185133563
4000 Elements Sorted by HeapSort in 0.13578669978414837
5000 Elements Sorted by HeapSort in 0.1658182863213824
6000 Elements Sorted by HeapSort in 0.1875901601906662
7000 Elements Sorted by HeapSort in 0.21982946862249264
8000 Elements Sorted by HeapSort in 0.2724293921580738
9000 Elements Sorted by HeapSort in 0.30996323029421546
Complexity PLot for Heap Sort is Given Below

Feeling lost in the world of random DSA topics, wasting time without progress? It's time for a change! Join our DSA course, where we'll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 geeks!
Last Updated :
31 Aug, 2022
Like Article
Save Article