Learn
We have all the methods we need in order to create our heapsort()
function!
Currently, our heapsort()
function does the following:
- Creates an empty list that will hold our sorted values.
- Creates an instance of
MaxHeap
. - Adds values from our parameter list into our
MaxHeap
instance.
In order to complete the function, here’s what we need to do:
- Create a
while
loop that iterates while our heap has at least one element. - Inside the loop, extract the largest value from the heap and place it at the beginning of the sorted list. Then, re-heapify the heap to ensure it maintains its heap properties.
- Return the sorted list.
Instructions
1.
Tab over to script.py.
Inside the heapsort()
function, create a while
loop that continues to execute while max_heap.count
is greater than 0
.
Within the while
loop, do the following:
- Create a variable called
max_value
and set it to the largest value in the heap. - Insert
max_value
to the beginning ofsort
.
2.
Finally, outside the while
loop, return sort
.
Note: Since we added a print statement to the end of our program, the code should output a sorted list!
Sign up to start coding
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.