Hi, can you please help me out.
At 8:27, we have a.age > b.age so when we compare 20 with 3 then it returns true right. So why are we swapping 20 and 3 to create min heap?
After 20 inserted heap is like
20
After 3 inserted heap is like
20
/
3
and then why 20 and 3 are changing position to form min heap
3
/
20
even though our function (a.age > b.age) returns true.
Thanks in advance.
Why swap occur even after returning true
@himanshugupta8 you answered your own question…
20
/
3
is not a min heap… this is why we need to swap 20 and 3
function returns true when we compare 20 and 3. So i want to know even though after function returns true why are we swapping 20 and 3.
@himanshugupta8
i think you are getting confused because you are linking this compare function to what you have seen in the sorting of linear data structures like arrays or vectors, but they are not the same. A heap is not a linear data structure, so its compare function will always behave differently.
Yes, i think i am a little confused. We pass our function so that heap can use this function for its comparing. So when 3 comes after 20, heap will use a.age = 20 > b.age = 3 which is going to return true. I don’t understand that even after returning true why are we swapping 20 and 3.
@himanshugupta8
compare function in heaps work differently.
if it returns true, then swap occurs.
Unlike an array when we dont swap if the compare function returns true.
Dont confuse the 2, they are very different data structures with different implementations.