-
Notifications
You must be signed in to change notification settings - Fork 118
/
HeapSort.cpp
50 lines (46 loc) · 959 Bytes
/
HeapSort.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
#include <bits/stdc++.h>
using namespace std;
void heap(vector<int> &A, int n, int i)
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && A[l] > A[largest])
largest = l;
if (r < n && A[r] > A[largest])
largest = r;
if (largest != i)
{
int t = A[i];
A[i] = A[largest];
A[largest] = t;
heap(A, n, largest);
}
}
void sort(vector<int> &A, int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
heap(A, n, i);
for (int i = n - 1; i > 0; i--)
{
int t = A[0];
A[0] = A[i];
A[i] = t;
heap(A, i, 0);
}
}
int main()
{
int n;
cout<<"Enter the number of elements: ";
cin>>n;
vector<int> A(n);
cout<<"Enter the elements: ";
for (int i = 0; i < n; i++)
cin>>A[i];
sort(A, n);
cout<<"Sorted array: ";
for (int i = 0; i < n; i++)
cout<<A[i]<<" ";
return 0;
}