Skip to content

Commit 790394b

Browse files
authored
Merge pull request #845 from debangi29/heap-sort
Added Heap Sort algorithm
2 parents 64c249e + 19f318b commit 790394b

File tree

1 file changed

+295
-0
lines changed

1 file changed

+295
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,295 @@
1+
---
2+
id: Heap-Sort
3+
title: Heap Sort (Geeks for Geeks)
4+
sidebar_label: Heap Sort
5+
tags:
6+
- Beginner
7+
- Sorting Algorithms
8+
- Geeks for Geeks
9+
- CPP
10+
- Python
11+
- Java
12+
- JavaScript
13+
- DSA
14+
description: "This is a solution to the Heap Sort problem on Geeks for Geeks."
15+
---
16+
17+
## 1. What is Heap Sort?
18+
19+
Heap sort is a comparison-based sorting technique based on Binary Heap data structure. It is similar to the selection sort where we first find the minimum element and place the minimum element at the beginning. Repeat the same process for the remaining elements.
20+
21+
## 2. Algorithm for Heap Sort
22+
23+
First convert the array into heap data structure using heapify, then one by one delete the root node of the Max-heap and replace it with the last node in the heap and then heapify the root of the heap. Repeat this process until size of heap is greater than 1.
24+
25+
1. Build a heap from the given input array.
26+
2. Repeat the following steps until the heap contains only one element:
27+
28+
- Swap the root element of the heap (which is the largest element) with the last element of the heap.
29+
- Remove the last element of the heap (which is now in the correct position).
30+
- Heapify the remaining elements of the heap.
31+
32+
3. The sorted array is obtained by reversing the order of the elements in the input array.
33+
34+
## 3. How does Heap Sort work?
35+
36+
To understand heap sort more clearly, let’s take an unsorted array and try to sort it using heap sort.
37+
38+
1. Build Complete Binary Tree: Build a complete binary tree from the array.
39+
40+
2. Transform into max heap: After that, the task is to construct a tree from that unsorted array and try to convert it into max heap.
41+
42+
3. To transform a heap into a max-heap, the parent node should always be greater than or equal to the child nodes
43+
44+
4. Perform heap sort: Remove the maximum element in each step (i.e., move it to the end position and remove that) and then consider the remaining elements and transform it into a max heap.
45+
46+
5. Delete the root element (10) from the max heap. In order to delete this node, try to swap it with the last node. After removing the root element, again heapify it to convert it into max heap.
47+
48+
6. Repeat the above steps. Now remove the root again and perform heapify.
49+
Now when the root is removed once again it is sorted
50+
51+
## 4. Problem Description
52+
53+
Given an array of integers, implement the Heap Sort algorithm to sort the array in ascending order.
54+
55+
## 5. Examples
56+
57+
**Example 1:**
58+
59+
```
60+
Input: [64, 34, 25, 12, 22, 11, 90]
61+
Output: [11, 12, 22, 25, 34, 64, 90]
62+
```
63+
64+
**Example 2:**
65+
66+
```
67+
Input: [5, 1, 4, 2, 8]
68+
Output: [1, 2, 4, 5, 8]
69+
```
70+
71+
## 6. Constraints
72+
73+
- The array can have any number of elements.
74+
- All elements in the array are integers.
75+
76+
## 7. Implementation
77+
78+
## Python
79+
<Tabs>
80+
<TabItem value="Python" label="Python" default>
81+
82+
```python
83+
84+
def heapify(arr, N, i):
85+
largest = i # Initialize largest as root
86+
l = 2 * i + 1 # left = 2*i + 1
87+
r = 2 * i + 2 # right = 2*i + 2
88+
89+
# See if left child of root exists and is
90+
# greater than root
91+
if l < N and arr[largest] < arr[l]:
92+
largest = l
93+
94+
# See if right child of root exists and is
95+
# greater than root
96+
if r < N and arr[largest] < arr[r]:
97+
largest = r
98+
99+
# Change root, if needed
100+
if largest != i:
101+
arr[i], arr[largest] = arr[largest], arr[i] # swap
102+
103+
# Heapify the root.
104+
heapify(arr, N, largest)
105+
106+
# The main function to sort an array of given size
107+
108+
def heapSort(arr):
109+
N = len(arr)
110+
111+
# Build a maxheap.
112+
for i in range(N//2 - 1, -1, -1):
113+
heapify(arr, N, i)
114+
115+
# One by one extract elements
116+
for i in range(N-1, 0, -1):
117+
arr[i], arr[0] = arr[0], arr[i] # swap
118+
heapify(arr, i, 0)
119+
120+
121+
```
122+
## C++
123+
124+
</TabItem>
125+
126+
<TabItem value="C++" label="C++">
127+
128+
```cpp
129+
130+
#include <iostream>
131+
using namespace std;
132+
void heapify(int arr[], int N, int i)
133+
{
134+
int largest = i;
135+
int l = 2 * i + 1;
136+
int r = 2 * i + 2;
137+
138+
139+
if (l < N && arr[l] > arr[largest])
140+
largest = l;
141+
142+
if (r < N && arr[r] > arr[largest])
143+
largest = r;
144+
145+
146+
if (largest != i) {
147+
swap(arr[i], arr[largest]);
148+
149+
heapify(arr, N, largest);
150+
}
151+
}
152+
153+
// Main function to do heap sort
154+
void heapSort(int arr[], int N)
155+
{
156+
157+
for (int i = N / 2 - 1; i >= 0; i--)
158+
heapify(arr, N, i);
159+
for (int i = N - 1; i > 0; i--) {
160+
swap(arr[0], arr[i]);
161+
heapify(arr, i, 0);
162+
}
163+
}
164+
165+
```
166+
## Java
167+
</TabItem>
168+
<TabItem value="Java" label="Java">
169+
170+
```java
171+
172+
public class HeapSort {
173+
public void sort(int arr[])
174+
{
175+
int N = arr.length;
176+
177+
// Build heap (rearrange array)
178+
for (int i = N / 2 - 1; i >= 0; i--)
179+
heapify(arr, N, i);
180+
181+
// One by one extract an element from heap
182+
for (int i = N - 1; i > 0; i--) {
183+
// Move current root to end
184+
int temp = arr[0];
185+
arr[0] = arr[i];
186+
arr[i] = temp;
187+
188+
// call max heapify on the reduced heap
189+
heapify(arr, i, 0);
190+
}
191+
}
192+
void heapify(int arr[], int N, int i)
193+
{
194+
int largest = i; // Initialize largest as root
195+
int l = 2 * i + 1; // left = 2*i + 1
196+
int r = 2 * i + 2; // right = 2*i + 2
197+
198+
// If left child is larger than root
199+
if (l < N && arr[l] > arr[largest])
200+
largest = l;
201+
202+
// If right child is larger than largest so far
203+
if (r < N && arr[r] > arr[largest])
204+
largest = r;
205+
206+
// If largest is not root
207+
if (largest != i) {
208+
int swap = arr[i];
209+
arr[i] = arr[largest];
210+
arr[largest] = swap;
211+
212+
// Recursively heapify the affected sub-tree
213+
heapify(arr, N, largest);
214+
}
215+
}
216+
}
217+
218+
```
219+
## JavaScript
220+
</TabItem>
221+
222+
<TabItem value="JavaScript" label="JavaScript">
223+
224+
```javascript
225+
function sort( arr)
226+
{
227+
var N = arr.length;
228+
229+
// Build heap (rearrange array)
230+
for (var i = Math.floor(N / 2) - 1; i >= 0; i--)
231+
heapify(arr, N, i);
232+
233+
// One by one extract an element from heap
234+
for (var i = N - 1; i > 0; i--) {
235+
// Move current root to end
236+
var temp = arr[0];
237+
arr[0] = arr[i];
238+
arr[i] = temp;
239+
240+
// call max heapify on the reduced heap
241+
heapify(arr, i, 0);
242+
}
243+
}
244+
245+
// To heapify a subtree rooted with node i which is
246+
// an index in arr[]. n is size of heap
247+
function heapify(arr, N, i)
248+
{
249+
var largest = i; // Initialize largest as root
250+
var l = 2 * i + 1; // left = 2*i + 1
251+
var r = 2 * i + 2; // right = 2*i + 2
252+
253+
// If left child is larger than root
254+
if (l < N && arr[l] > arr[largest])
255+
largest = l;
256+
257+
// If right child is larger than largest so far
258+
if (r < N && arr[r] > arr[largest])
259+
largest = r;
260+
261+
// If largest is not root
262+
if (largest != i) {
263+
var swap = arr[i];
264+
arr[i] = arr[largest];
265+
arr[largest] = swap;
266+
267+
// Recursively heapify the affected sub-tree
268+
heapify(arr, N, largest);
269+
}
270+
}
271+
````
272+
273+
</TabItem>
274+
</Tabs>
275+
276+
## 8. Complexity Analysis
277+
278+
- Time Complexity: $O(N log N)$
279+
- Auxiliary Space: $O(log n)$, due to the recursive call stack. However, auxiliary space can be $O(1)$ for iterative implementation.
280+
281+
## 9. Advantages and Disadvantages
282+
283+
**Advantages:**
284+
- **Efficient Time Complexity**: Heap Sort has a time complexity of $O(n log n)$ in all cases. This makes it efficient for sorting large datasets. The log n factor comes from the height of the binary heap, and it ensures that the algorithm maintains good performance even with a large number of elements.
285+
- **Memory Usage** – Memory usage can be minimal (by writing an iterative heapify() instead of a recursive one). So apart from what is necessary to hold the initial list of items to be sorted, it needs no additional memory space to work
286+
- **Simplicity** – It is simpler to understand than other equally efficient sorting algorithms because it does not use advanced computer science concepts such as recursion.
287+
288+
**Disadvantages:**
289+
- **Costly**: Heap sort is costly as the constants are higher compared to merge sort even if the time complexity is $O(n Log n)$ for both.
290+
- **Unstable**: Heap sort is unstable. It might rearrange the relative order.
291+
- **Efficiency**: Heap Sort is not very efficient when working with highly complex data.
292+
293+
## 10. References
294+
295+
- **GFG Problem:** [GFG Problem](https://www.geeksforgeeks.org/Heap-sort/)

0 commit comments

Comments
 (0)