-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDS-3.1.MakeHeap.cpp
More file actions
48 lines (40 loc) · 864 Bytes
/
DS-3.1.MakeHeap.cpp
File metadata and controls
48 lines (40 loc) · 864 Bytes
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
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
int c;
vector < pair <int , int > > v;
void heapify(int arr[], int n, int i)
{
int smallest = i,l,r;
l=2*i+1;
r=2*i+2;
if(l<n&&arr[l]<arr[smallest])
smallest =l;
if(r<n&&arr[r]<arr[smallest])
smallest=r;
if(smallest!=i&&smallest<n)
{
v.push_back(make_pair(i,smallest));
swap(arr[smallest], arr[i]);
heapify(arr,n,smallest);
c++;
}
}
void heapsort(int arr[], int n)
{
for(int i=n/2-1;i>=0;i--)
heapify(arr,n,i);
cout<<c<<endl;
for(int i=0;i<c;i++)
cout<<v[i].first<<" "<<v[i].second<<endl;
}
int main()
{
int n;
c=0;
cin>>n;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
heapsort(arr,n);
}