Workspace Convert Min Heap To Max Heap
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Convert Min Heap to Max Heap visualizer

Learn Convert Min Heap to Max Heap with a step-by-step Heaps visualizer, JavaScript source code and a worked example. Practice priority queues and top k.

INTERACTIVE EXECUTION STUDIO
LEARN BY DOING

Predict. Execute. Understand.

Follow the source code, inspect live state changes, and predict the next operation before revealing it.

1 / 4Execution step
Reference example · JavaScript
Inspect reference input
[
  1,
  3,
  2,
  5,
  4
]

Algorithm source

JavaScript reference implementation · highlighted trace statement
const solve = (a,s)=>{
function down(i){
while(true){
let b=i,l=2*i+1,r=l+1;
if(l<a.length&&a[l]>a[b])b=l;
if(r<a.length&&a[r]>a[b])b=r;
if(b===i)return;
[a[i],a[b]]=[a[b],a[i]];
s("Sift larger child upward",{
Heap:a
},[i,b]);
i=b
}
}
for(let i=Math.floor(a.length/2)-1;
i>=0;
i--)down(i);
return a
};

Execution canvas

Active Changed
STEP 1

Sift larger child upward

Inspect the highlighted code and the state below. Click individual cells or nodes to see their values.

Heap5 items
Keyboard: Space to play · Left / Right to stepExplore next problem

Worked example and algorithm walkthrough

Topic: Heaps · Priority queues and top K

Follow the computed execution on the reference input. Advance one step at a time, inspect the changing values and compare your prediction with the final output.

Example input

[
  1,
  3,
  2,
  5,
  4
]

Execution steps

  1. Sift larger child upward

Computed output

[
  5,
  4,
  2,
  3,
  1
]
JavaScript reference implementation
const solve = (a,s)=>{
  function down(i){
    while(true){
      let b=i,l=2*i+1,r=l+1;
      if(l<a.length&&a[l]>a[b])b=l;
      if(r<a.length&&a[r]>a[b])b=r;
      if(b===i)return;
      [a[i],a[b]]=[a[b],a[i]];
      s("Sift larger child upward",{
        Heap:a
      },[i,b]);
      i=b
    }
  }
  for(let i=Math.floor(a.length/2)-1;
  i>=0;
  i--)down(i);
  return a
};

Continue learning

Practice related DSA questions in the same topic.