Open In App

Python Code for time Complexity plot of Heap Sort

Last Updated : 31 Aug, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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




# 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 function
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


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



Previous Article
Next Article

Similar Reads

Difference between Binary Heap, Binomial Heap and Fibonacci Heap
Binary Heap:A Binary Heap is a Binary Tree with following properties. It’s a complete binary tree i.e., all levels are completely filled except possibly the last level and the last level has all keys as left as possible. This property of Binary Heap makes them suitable to be stored in an array. A Binary Heap is either Min Heap or Max Heap. In a Min
2 min read
C program for Time Complexity plot of Bubble, Insertion and Selection Sort using Gnuplot
Prerequisite:Comparison among bubble sort, insertion sort and selection sort. Write a C program to plot and analyze the time complexity of Bubble sort, Insertion sort and Selection sort (using Gnuplot). As per the problem we have to plot a time complexity graph by just using C. So we will be making sorting algorithms as functions and all the algori
5 min read
Time Complexity and Space Complexity
Generally, there is always more than one way to solve a problem in computer science with different algorithms. Therefore, it is highly required to use a method to compare the solutions in order to judge which one is more optimal. The method must be: Independent of the machine and its configuration, on which the algorithm is running on.Shows a direc
14 min read
Time Complexity of building a heap
Consider the following algorithm for building a Heap of an input array A. BUILD-HEAP(A) heapsize := size(A); for i := floor(heapsize/2) downto 1 do HEAPIFY(A, i); end for END A quick look over the above algorithm suggests that the running time is [Tex]O(n * lg(n)) [/Tex] since each call to Heapify costs [Tex]O(lg(n)) [/Tex]and Build-Heap makes [Tex
2 min read
Heap Sort for decreasing order using min heap
Given an array of elements, sort the array in decreasing order using min heap. Examples: Input : arr[] = {5, 3, 10, 1} Output : arr[] = {10, 5, 3, 1} Input : arr[] = {1, 50, 100, 25} Output : arr[] = {100, 50, 25, 1} Prerequisite: Heap sort using min heap. Algorithm : Build a min heap from the input data. At this point, the smallest item is stored
13 min read
Time Series Plot or Line plot with Pandas
Prerequisite: Create a Pandas DataFrame from Lists Pandas is an open-source library used for data manipulation and analysis in Python. It is a fast and powerful tool that offers data structures and operations to manipulate numerical tables and time series. Examples of these data manipulation operations include merging, reshaping, selecting, data cl
6 min read
Pandas - Plot multiple time series DataFrame into a single plot
In this article, we are going to see how to plot multiple time series Dataframe into single plot. If there are multiple time series in a single DataFrame, you can still use the plot() method to plot a line chart of all the time series. To Plot multiple time series into a single plot first of all we have to ensure that indexes of all the DataFrames
4 min read
Complexity analysis of various operations of Binary Min Heap
A Min Heap is a Complete Binary Tree in which the children nodes have a higher value (lesser priority) than the parent nodes, i.e., any path from the root to the leaf nodes, has an ascending order of elements. In the case of a binary tree, the root is considered to be at height 0, its children nodes are considered to be at height 1, and so on. Each
3 min read
Time and Space complexity analysis of Selection Sort
The Selection sort algorithm has a time complexity of O(n^2) and a space complexity of O(1) since it does not require any additional memory space apart from a temporary variable used for swapping. Time Complexity Analysis of Selection Sort:Best-case: O(n2), best case occurs when the array is already sorted. (where n is the number of integers in an
2 min read
Time complexity of insertion sort when there are O(n) inversions?
What is an inversion? Given an array arr[], a pair arr[i] and arr[j] forms an inversion if arr[i] j. For example, the array {1, 3, 2, 5} has one inversion (3, 2) and array {5, 4, 3} has inversions (5, 4), (5, 3) and (4, 3). We have discussed a merge sort based algorithm to count inversions What is the time complexity of Insertion Sort when there ar
1 min read
three90RightbarBannerImg