Skip to content

Commit 5dd3e6e

Browse files
committed
Heap Sort
1 parent 89b819d commit 5dd3e6e

File tree

2 files changed

+78
-1
lines changed

2 files changed

+78
-1
lines changed

DSA Crack Sheet/README.md

+1-1
Original file line numberDiff line numberDiff line change
@@ -283,7 +283,7 @@
283283
### Heap
284284

285285
- [Building Heap from Array](https://www.geeksforgeeks.org/building-heap-from-array/ "view post")
286-
- []( "view question") - [Cpp Solution](./solutions/.cpp)
286+
- [Heap Sort](https://practice.geeksforgeeks.org/problems/heap-sort/1# "view question") - [Cpp Solution](./solutions/Heap%20Sort.cpp)
287287
- []( "view question") - [Cpp Solution](./solutions/.cpp)
288288

289289
### Graphs
+77
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
/*
2+
Heap Sort
3+
=========
4+
5+
Given an array of size N. The task is to sort the array elements by completing functions heapify() and buildHeap() which are used to implement Heap Sort.
6+
7+
Example 1:
8+
Input:
9+
N = 5
10+
arr[] = {4,1,3,9,7}
11+
Output:
12+
1 3 4 7 9
13+
Explanation:
14+
After sorting elements
15+
using heap sort, elements will be
16+
in order as 1,3,4,7,9.
17+
18+
Example 2:
19+
Input:
20+
N = 10
21+
arr[] = {10,9,8,7,6,5,4,3,2,1}
22+
Output:
23+
1 2 3 4 5 6 7 8 9 10
24+
Explanation:
25+
After sorting elements
26+
using heap sort, elements will be
27+
in order as 1, 2,3,4,5,6,7,8,9,10.
28+
29+
Your Task :
30+
You don't have to read input or print anything. Your task is to complete the functions heapify(), buildheap() and heapSort() where heapSort() and buildheap() takes the array and it's size as input and heapify() takes the array, it's size and an index i as input. Complete and use these functions to sort the array using heap sort algorithm.
31+
32+
Expected Time Complexity: O(N * Log(N)).
33+
Expected Auxiliary Space: O(1).
34+
35+
Constraints:
36+
1 <= N <= 106
37+
1 <= arr[i] <= 106
38+
*/
39+
40+
//Heapify function to maintain heap property.
41+
void heapify(int A[], int n, int i)
42+
{
43+
int large = i;
44+
int left = 2 * i + 1, right = 2 * i + 2;
45+
46+
if (left < n && A[large] < A[left])
47+
large = left;
48+
if (right < n && A[large] < A[right])
49+
large = right;
50+
51+
// large me largest wale ka index hai hai teeno me se
52+
if (large == i)
53+
return;
54+
swap(A[large], A[i]);
55+
heapify(A, n, large);
56+
}
57+
58+
public:
59+
//Function to build a Heap from array.
60+
void buildHeap(int A[], int n)
61+
{
62+
// internal nodes are from n/2-1 to 0
63+
for (int i = n / 2 - 1; i >= 0; --i)
64+
heapify(A, n, i);
65+
}
66+
67+
public:
68+
//Function to sort an array using Heap Sort.
69+
void heapSort(int A[], int n)
70+
{
71+
buildHeap(A, n);
72+
for (int i = n - 1; i > 0; --i)
73+
{
74+
swap(A[0], A[i]);
75+
heapify(A, i, 0);
76+
}
77+
}

0 commit comments

Comments
 (0)