-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheapSort.cpp
89 lines (64 loc) · 1.22 KB
/
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
#include<bits/stdc++.h>
using namespace std;
class pair_def
{
vector<pair<int,int>> arr;
public:
void input(int n)
{
int i;
int a,b;
cout<<"\n"<<"Enter key and value";
for(i = 0;i < n;i++)
{
cin>>a>>b;
arr.push_back(make_pair(a,b));
}
}
void heapify(int i,int n)
{
int r = 2*i + 2,l = 2*i + 1,largest = i;
pair<int,int> t;
if (l < n && arr[largest]<arr[l])
largest = l;
if (r < n && arr[largest]<arr[r])
largest = r;
if (largest != i)
{
t = arr[i];
arr[i] = arr[largest];
arr[largest] = t;
heapify(largest,n);
}
}
void heapSort()
{
pair<int,int> t;
int n = arr.size(),i;
for (i = n / 2 - 1; i >= 0; i--)
heapify( i,n);
for (i=n-1; i > 0; i--)
{
t = arr[0];
arr[0] = arr[i];
arr[i] = t;
heapify(0,i);
}
}
void print()
{
cout<<"\n"<<"The sorted array is:";
for(int i = 0;i < arr.size();i++)
{
cout<<arr[i].first<<" "<<arr[i].second<<"\n";
}
}
};
int main()
{
pair_def a;
a.input(5);
a.heapSort();
a.print();
//cout<<(make_pair(2,2)<make_pair(1,3));
}