Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

10.8 Heapify a Vector. The heapify operation converts an arrayof values into a valid max-heap form. In this lab, you'll performheapify on a vector of

10.8 Heapify a Vector. The heapify operation converts an arrayof values into a valid max-heap form. In this lab, you'll performheapify on a vector of integers:

void heapify(std::vector &v, int &diff); // FunctionPrototype

The function takes a reference to a vector as an argument andheapifies it according to the heapify logic described below. Also,your function should calculate how many positions in the vectorchanged value as compared to the starting point. This value shouldbe returned in the diff variable.

Logic for computing the diff variable = for each position in thenew and old vector: if the positions have different value:diff++

Driver Function:

int main()
{
vector v = {20, 19, 100, 2};
int diff = 0;
heapify(v, diff);
cout << "Different in " << diff << " positions.Heap: ";
for(int i: v)
cout << i << ", ";
cout << endl;
return 0;
}

Heapify Logic: (pseudocode)

heapify() {

m = get the last used internal node index // everything after isa leaf

while( m >= 0 ) {

MaxHeapPercolateDown(m);

m--;

}

}

MaxHeapPercolateDown(nodeIndex, size) {

val = heapArray[nodeIndex]; //nodeIndex starts as 0

child_index = nodeIndex*2+1; // get first child index

while(child_index < size){

max_val = val;

max_index = -1;

for (i=child_index; i

if(heapArray[i] >max_val) {

max_val =heapArray[i];

max_index= i;

}

if (max_val == val) return; // nothingelse to do

swap(max_index,nodeIndex);

nodeIndex = max_index;

child_index = 2*nodeIndex + 1;

}

}

** Use the given logic and driver function to implement: voidheapify(std::vector &v, int &diff);

Step by Step Solution

There are 3 Steps involved in it

Step: 1

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Computer Performance Engineering 10th European Workshop Epew 2013 Venice Italy September 17 2013 Proceedings

Authors: Maria Simonetta Balsamo ,William Knottenbelt ,Andrea Marin

2013 Edition

3642407242, 978-3642407246

More Books

Students also viewed these Programming questions

Question

How does stock price maximization benefit society?

Answered: 1 week ago

Question

How are interest rates used to allocate capital among firms?

Answered: 1 week ago