I Need Help Understanding a Concept

Observe the heapify_up() method. You will see that there is a line of code where the parent element is set equal to its child. Does this switch the index of the parent and child:

<self.heap_list[self.parent_idx(idx)] = self.heap_list[idx]>

https://www.codecademy.com/paths/computer-science/tracks/complex-data-structures/modules/cspath-heaps/lessons/python-heaps/exercises/python-heaps-retrieve-min

And how do you write code on this post?

Hi – To post code, use the </> icon in the middle of the menu bar that appears at the top of the text box you are typing in.

self.heap_list[self.parent_idx(idx)] = self.heap_list[idx]

Since it’s a min-heap, you want parent value to be less than child value, so, yes if parent value is greater than child value, you need to swap the two.

Since in the heap, the parent - child relationship is defined by the indexing system, what you need to do is swap the values stored at those two indices.

The line above accomplishes part of that swap; it overwrites the value stored at the parent index with that stored at the child index. You also need a temp variable step to store the overwritten value so it can be re-written into the child index.

Recall that Python permits inline swapping…

a, b = b, a