- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Python Program for Heap Sort
In this article, we will learn about the solution to the problem statement given below.
Problem statement − We are given an array, we need to sort it using the concept of heapsort.
Here we place the maximum element at the end. This is repeated until the array is sorted.
Now let’s observe the solution in the implementation below−
Example
# heapify def heapify(arr, n, i): largest = i # largest value l = 2 * i + 1 # left r = 2 * i + 2 # right # if left child exists if l < n and arr[i] < arr[l]: largest = l # if right child exits if r < n and arr[largest] < arr[r]: largest = r # root if largest != i: arr[i],arr[largest] = arr[largest],arr[i] # swap # root. heapify(arr, n, largest) # sort def heapSort(arr): n = len(arr) # maxheap for i in range(n, -1, -1): heapify(arr, n, i) # element extraction for i in range(n-1, 0, -1): arr[i], arr[0] = arr[0], arr[i] # swap heapify(arr, i, 0) # main arr = [2,5,3,8,6,5,4,7] heapSort(arr) n = len(arr) print ("Sorted array is") for i in range(n): print (arr[i],end=" ")
Output
Sorted array is 2 3 4 5 5 6 7 8
All the variables are declared in the local scope and their references are seen in the figure above.
Conclusion
In this article, we have learned about how we can make a Python Program for Heap Sort
- Related Articles
- C++ Program to Implement Heap Sort
- What is Heap Sort in Python?
- Heap Sort
- Python Program for Bubble Sort
- Python Program for Insertion Sort
- Python Program for Selection Sort
- Python Program for Cocktail Sort
- Python Program for Counting Sort
- Python Program for Cycle Sort
- Python Program for Gnome Sort
- Python Program for Merge Sort
- Python Program for Stooge Sort
- Python Program for Odd-Even Sort / Brick Sort
- Heap Sort in C#
- C++ Program to Sort an Array of 10 Elements Using Heap Sort Algorithm

Advertisements