-
Notifications
You must be signed in to change notification settings - Fork 0
/
tut156.c++
87 lines (69 loc) · 1.48 KB
/
tut156.c++
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
/*Convert min Heap to max Heap -> Given array representation of min Heap, convert it to max Heap in O(n) time.
Example:
Input: arr[] = [3 5 9 6 8 20 10 12 18 9]
3
/ \
5 9
/ \ / \
6 8 20 10
/ \ /
12 18 9
Output: arr[] = [20 18 10 12 9 9 3 5 6 8] OR [any Max Heap formed from input elements]
20
/ \
18 10
/ \ / \
12 9 9 3
/ \ /
5 6 8
*/
#include <bits/stdc++.h>
using namespace std;
void heapify(int arr[], int i, int n)
{
if (i >= n)
{
return;
}
int parent = i;
int leftChild = 2 * i + 1;
int rightChild = 2 * i + 2;
if (leftChild < n && arr[leftChild] > arr[parent])
{
parent = leftChild; // changing index
}
if (rightChild < n && arr[rightChild] > arr[parent])
{
parent = rightChild; // changing index
}
if (parent != i)
{
swap(arr[i], arr[parent]);
heapify(arr, parent, n);
}
}
void convertMaxHeap(int arr[], int n)
{
for (int i = n / 2 - 1; i >= 0; i--)
{
heapify(arr, i, n);
}
}
void printArray(int arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout << arr[i] << " ";
}
}
int main()
{
int arr[] = {3, 5, 9, 6, 8, 20, 10, 12, 18, 9};
int n = sizeof(arr) / sizeof(arr[0]);
printf("Min Heap array : ");
printArray(arr, n);
convertMaxHeap(arr, n);
printf("\nMax Heap array : ");
printArray(arr, n);
return 0;
}