Converting maxheap to minheap

Nov 3, 2019 at 10:32pm
Hye! What changes I must make to convert the max heap funtion "heapify" to min heap! Thanks

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
// C++ program for implement deletion in Heaps 

#include <iostream> 

using namespace std; 

// To heapify a subtree rooted with node i which is 
// an index in arr[]. N is size of heap 
void heapify(int arr[], int n, int i) 
{ 
	int largest = i; // Initialize largest as root 
	int l = 2 * i + 1; // left = 2*i + 1 
	int r = 2 * i + 2; // right = 2*i + 2 

	// If left child is larger than root 
	if (l < n && arr[l] > arr[largest]) 
		largest = l; 

	// If right child is larger than largest so far 
	if (r < n && arr[r] > arr[largest]) 
		largest = r; 

	// If largest is not root 
	if (largest != i) { 
		swap(arr[i], arr[largest]); 

		// Recursively heapify the affected sub-tree 
		heapify(arr, n, largest); 
	} 
} 

// Function to delete the root from Heap 
void deleteRoot(int arr[], int& n) 
{ 
	// Get the last element 
	int lastElement = arr[n - 1]; 

	// Replace root with first element 
	arr[0] = lastElement; 

	// Decrease size of heap by 1 
	n = n - 1; 

	// heapify the root node 
	heapify(arr, n, 0); 
} 

/* A utility function to print array of size n */
void printArray(int arr[], int n) 
{ 
	for (int i = 0; i < n; ++i) 
		cout << arr[i] << " "; 
	cout << "\n"; 
} 

// Driver Code 
int main() 
{ 
	// Array representation of Max-Heap 
	// 10 
	// / \ 
	// 5 3 
	// / \ 
	// 2 4 
	int arr[] = { 10, 5, 3, 2, 4 }; 

	int n = sizeof(arr) / sizeof(arr[0]); 

	deleteRoot(arr, n); 

	printArray(arr, n); 

	return 0; 
} 
Nov 3, 2019 at 11:08pm
I will continue under the assumption that you wrote that code.
Therefore, you should have a basic understanding of the heap property that you coded into it.

What is the heap property?
How does it affect the heap?

Answer those questions and you will be able to invert the heap from a max-heap to a min-heap.


Super Extra Special Kaiber Monkey Force Mega Hint:
http://www.cplusplus.com/faq/sequences/sequencing/sort-algorithms/heapsort/#heap-property
Topic archived. No new replies allowed.