-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGoogle.cpp
More file actions
63 lines (61 loc) · 1.41 KB
/
Google.cpp
File metadata and controls
63 lines (61 loc) · 1.41 KB
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
// Complexity of this prblem is O(n) & Space Complexity is O(1) or O(n)
void Heapify(long *arr,int n,int i){
long largest=i;
long left=2*i+1;
long right=2*i+2;
if(left<n && arr[largest]<arr[left]){
largest=left;
}
if(right<n && arr[largest]<arr[right]){
largest=right;
}
// checking the parent Node of its right position
if(largest!=i){
swap(arr[largest],arr[i]);
Heapify(arr,n,largest);
}
}
void minHeapToMaxHeap(long *arr, int n)
{
for(int i=n/2;i>=0;i--){
Heapify(arr,n,i);
}
}
// Second varient of its problem
#include<bits/stdc++.h>
using namespace std;
class Solution {
void Heapify(int *arr,int n,int i){
int largest=i;
int left=2*i+1;
int right=2*i+2;
if(left<n && arr[largest]<arr[left]){
largest=left;
}
if(right<n && arr[largest]<arr[right]){
largest=right;
}
// checking the parent Node of its right position
if(largest!=i){
swap(arr[largest],arr[i]);
Heapify(arr,n,largest);
}
}
public:
vector<int> convertToMaxHeap(vector<int>& arr) {
int n=arr.size();
int Arr[n];
int j=0;
for(int i:arr){
Arr[j++]=i;
}
for(int i=n/2;i>=0;i--){
Heapify(Arr,n,i);
}
vector<int>ans;
for(int i=0;i<n;i++){
ans.push_back(Arr[i]);
}
return ans;
}
};