Answer to Question #204259 in Algorithms for Haider

Question #204259

What is heap. Create maximum heap using built in function or using array list. Use any one method for creation max heap.



1
Expert's answer
2021-06-08T17:27:25-0400

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);
    }
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS