What is heap. Create maximum heap using built in function or using array list. Use any one method for creation max heap.
Heap: A heap is a specialized tree based data structure in which all the nodes of the tree in a specific order.
void heapify(int arr[], int n, int i)
{
int largest = i;
int l = 2 * i + 1;
int r = 2 * i + 2;
if (l < n && arr[l] > arr[largest])
largest = l;
if (r < n && arr[r] > arr[largest])
largest = r;
if (largest != i) {
swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
Creation of the maximum heap:
void buildHeap(int arr[], int n)
{
// index node of non-leaf node
int startIdx = (n / 2) - 1;
for (int i = startIdx; i >= 0; i--) {
heapify(arr, n, i);
}
}
Comments
Leave a comment