forked from Shreyasheeetal20/HACKTOBERFEST22
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Heap_Sort.cpp
62 lines (53 loc) · 1.12 KB
/
Heap_Sort.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Heap Sort Code in C++
#include <bits/stdc++.h>
using namespace std;
void printArray(vector<int> &v)
{
for (auto i : v)
{
cout << i << " ";
}
cout << endl;
}
void heapify(vector<int> &v, int n, int i)
{
int Largest = i;
int Left_Child = 2 * i + 1;
int Right_Child = 2 * i + 2;
if (Left_Child < n && v[Left_Child] > v[Largest])
Largest = Left_Child;
if (Right_Child < n && v[Right_Child] > v[Largest])
Largest = Right_Child;
if (Largest != i)
{
swap(v[i], v[Largest]);
heapify(v, n, Largest);
}
}
void heapSort(vector<int> &v, int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heapify(v, n, i);
for (int i = n - 1; i >= 0; i--)
{
swap(v[0], v[i]);
heapify(v, i, 0);
}
}
int main()
{
int n;
cout << "Enter the size of Array : ";
cin >> n;
vector<int> numbers(n);
cout << "Enter the elements of the array : ";
for (auto i = 0; i < n; i++)
{
int x;
cin >> x;
numbers[i] = x;
}
heapSort(numbers, n);
cout << "Sorted array : ";
printArray(numbers);
}