NOTE: I am beginner in Python
I learnt the Heap sort today and tried my own implementation using Python. Can i get feedback for my code and areas of improvement. I have tried to add comments inline, but if still something is unclear, then i will add more comments.
def max_heap(listmax):
i = 1
# if there is only one node, so thats is the max heap
# for only 1 node, it wont go inside while loop and max heap will be node itself
while i <= len(listmax) -1:
# for 2 nodes of more, the parent is checked against child
# when there are 2 nodes, i will have max 1 value = len(listmax) - 1
# j is actually the parent of i, i can have 2 children which will have odd and even index
# for eg. if 3 nodes, i can be 0,1,2 so 0 is parent and 1,2 will be children
if i%2 == 0:
j = int(i/2 -1)
else:
j = int(i//2)
# here the listmax[i] will have the value of child node and listmax[j] has value of parent
# if the parent > children, then else is executed which moves to the next child of the parent
if listmax[i] > listmax[j]:
listmax[i],listmax[j] = listmax[j],listmax[i]
# the i > 2 is there because then only, the children can become parents, and hence i make
# the children as parents and compare it further up
# the children are made parent by the below logic
if i > 2:
if i%2 == 0:
i = int(i/2 -1)
else:
i = int(i//2)
else:
i = i +1
else:
i = i +1
return listmax
def sort_heap(randomlist):
max_heap_tree = max_heap(randomlist)
sorted_heap = []
sorted_heap.append(max_heap_tree[0])
while len(max_heap_tree) > 1:
# the next highest number is found using the max_heap by removing the [0] element from the list
max_heap_tree = max_heap(max_heap_tree[1:])
sorted_heap.append(max_heap_tree[0])
return sorted_heap
randomlist = [10,15,30,12,15,20,17,20,32]
sort_heap(randomlist)