Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Lexicographical ordering using Heap Sort
Next article icon

Heap Sort – Python

Last Updated : 03 Mar, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Heapsort is a comparison-based sorting technique based on a 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 the remaining element.

Heap Sort Algorithm

First convert the array into a max heap using heapify, Please note that this happens in-place. The array elements are re-arranged to follow heap properties. Then one by one delete the root node of the Max-heap and replace it with the last node and heapify. Repeat this process while size of heap is greater than 1.

  • Rearrange array elements so that they form a Max Heap.
  • Repeat the following steps until the heap contains only one element:
    • Swap the root element of the heap (which is the largest element in current heap) with the last element of the heap.
    • Remove the last element of the heap (which is now in the correct position). We mainly reduce heap size and do not remove element from the actual array.
    • Heapify the remaining elements of the heap.
  • Finally we get sorted array.

Working of Heap Sort

Step 1: Treat the Array as a Complete Binary Tree

We first need to visualize the array as a complete binary tree. For an array of size n, the root is at index 0, the left child of an element at index i is at 2i + 1, and the right child is at 2i + 2.

Visualize-the-array-as-a-complete-binary-tree

Array as Binary Tree

Step 2: Build a Max Heap

Below are the detailed steps to heapify the tree:

Step 3: Sort the array by placing largest element at end of unsorted array.

Below are the detailed steps to sort the array:

In the illustration above, we have shown some steps to sort the array. We need to keep repeating these steps until there’s only one element left in the heap.

The given Python code implements the Heap Sort algorithm, which is an efficient comparison-based sorting method.

Python
def heapify(arr, n, i):     largest = i  # Initialize largest as root     l = 2 * i + 1  # left = 2*i + 1     r = 2 * i + 2  # right = 2*i + 2   # See if left child of root exists and is  # greater than root      if l < n and arr[i] < arr[l]:         largest = l   # See if right child of root exists and is  # greater than root      if r < n and arr[largest] < arr[r]:         largest = r   # Change root, if needed      if largest != i:         (arr[i], arr[largest]) = (arr[largest], arr[i])  # swap    # Heapify the root.          heapify(arr, n, largest)   # The main function to sort an array of given size  def heapSort(arr):     n = len(arr)   # Build a maxheap.  # Since last parent will be at (n//2) we can start at that location.      for i in range(n // 2, -1, -1):         heapify(arr, n, i)   # One by one extract elements      for i in range(n - 1, 0, -1):         (arr[i], arr[0]) = (arr[0], arr[i])  # swap         heapify(arr, i, 0)   # Driver code to test above  arr = [12, 11, 13, 5, 6, 7, ] heapSort(arr) n = len(arr) print('Sorted array is') for i in range(n):     print(arr[i]) 

Output
Sorted array is 5 6 7 11 12 13 

Time Complexity: O(n*log(n))

  • The time complexity of heapify is O(log(n)).
  • Time complexity of createAndBuildHeap() is O(n).
  • And, hence the overall time complexity of Heap Sort is O(n*log(n)).

Auxiliary Space: O(log(n))

Using Python STL

Steps:

  1. Import the Python STL library “heapq“.
  2. Convert the input list into a heap using the “heapify” function from heapq.
  3. Create an empty list “result” to store the sorted elements.
  4. Iterate over the heap and extract the minimum element using “heappop” function from heapq and append it to the “result” list.
  5. Return the “result” list as the sorted output.
Python
import heapq  # Function to perform the sorting using # heaop sort def heap_sort(arr):     heapq.heapify(arr)     result = []     while arr:         result.append(heapq.heappop(arr))     return result    # Driver Code arr = [60, 20, 40, 70, 30, 10] print("Input Array: ", arr) print("Sorted Array: ", heap_sort(arr)) 

Output
Input Array:  [60, 20, 40, 70, 30, 10] Sorted Array:  [10, 20, 30, 40, 60, 70]

Time Complexity: O(n log n), where “n” is the size of the input list. 
Auxiliary Space: O(1).

Please refer complete article on Heap Sort for more details!



Next Article
Lexicographical ordering using Heap Sort
author
kartik
Improve
Article Tags :
  • DSA
  • Heap
  • Python Programs
  • Sorting
  • Heap Sort
  • python sorting-exercises
  • Python-DSA
Practice Tags :
  • Heap
  • Sorting

Similar Reads

  • Heap Sort - Data Structures and Algorithms Tutorials
    Heap sort is a comparison-based sorting technique based on Binary Heap Data Structure. It can be seen as an optimization over selection sort where we first find the max (or min) element and swap it with the last (or first). We repeat the same process for the remaining elements. In Heap Sort, we use
    14 min read
  • Iterative HeapSort
    HeapSort is a comparison-based sorting technique where we first build Max Heap and then swap the root element with the last element (size times) and maintains the heap property each time to finally make it sorted. Examples: Input : 10 20 15 17 9 21 Output : 9 10 15 17 20 21 Input: 12 11 13 5 6 7 15
    11 min read
  • Java Program for Heap Sort
    Heap sort is a comparison-based sorting technique based on the Binary Heap data structure. It is similar to the selection sort where first find the maximum element and place it at the end. We repeat the same process for the remaining element. Heap Sort in JavaBelow is the implementation of Heap Sort
    3 min read
  • C++ Program for Heap Sort
    Heap sort is a comparison-based sorting technique based on the Binary Heap data structure. It is similar to the selection sort where we first find the maximum element and place the maximum element at the end. We repeat the same process for the remaining element. Recommended PracticeHeap SortTry It!
    3 min read
  • sort_heap function in C++
    The sort_heap( ) is an STL algorithm which sorts a heap within the range specified by start and end. Sorts the elements in the heap range [start, end) into ascending order. The second form allows you to specify a comparison function that determines when one element is less than another. Defined in h
    3 min read
  • Heap Sort - Python
    Heapsort is a comparison-based sorting technique based on a 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 the remaining element. Heap Sort AlgorithmFirst convert the array i
    4 min read
  • Lexicographical ordering using Heap Sort
    Given an array arr[] of strings. The task is to sort the array in lexicographical order using Heap Sort.Examples: Input: arr[] = { "banana", "apple", "mango", "pineapple", "orange" } Output: apple banana mango orange pineappleInput: arr[] = { "CAB", "ACB", "ABC", "CBA", "BAC" } Output: ABC, ACB, BAC
    10 min read
  • Heap sort for Linked List
    Given a linked list, the task is to sort the linked list using HeapSort. Examples: Input: list = 7 -> 698147078 -> 1123629290 -> 1849873707 -> 1608878378 -> 140264035 -> -1206302000Output: -1206302000 -> 7 -> 140264035 -> 1123629290 -> 1608878378 -> 1698147078 ->1
    14 min read
  • Python Code for time Complexity plot of Heap Sort
    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 he
    3 min read
  • Sorting algorithm visualization : Heap Sort
    An algorithm like Heap sort can be understood easily by visualizing. In this article, a program that visualizes the Heap Sort Algorithm has been implemented. The Graphical User Interface(GUI) is implemented in Python using pygame library. Approach: Generate random array and fill the pygame window wi
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences