I have implemented basic max heap insertion and deletion functions without recursion
# insertion
arr: [6,5,4,3,2,1]
# insert 7
arr: [7,5,6,3,2,1,4]
tree:
7
5 6
3 2 1 4
# delete 7
arr: [6,5,4,3,2,1]
tree:
6
5 4
3 2 1
My implementation
def insert(arr,ele):
# bottom up
n = len(arr)
# insert into the n+1 position
new_arr = arr.append(ele)
i = n # last position
while True:
p_index = int((i-1)/2)
# compare with the parent index
if (arr[i] > arr[p_index]):
# swap the elements
arr[p_index], arr[i] = arr[i], arr[p_index]
i = p_index
else:
# correct
break
return arr
# deletion
def delete(arr):
# top down
if not arr:
return None
# swap the last elment to root
arr[0], arr[len(arr)-1] = arr[len(arr)-1], arr[0]
item = arr.pop()
n = len(arr)
i = 0
# comparing the children
while True:
# left/right child index
lc_index = 2*i + 1
rc_index = 2*i + 2
# no chilren
if lc_index > n-1:
break
# only has left child
if lc_index == (n-1) and rc_index > n-1:
if arr[lc_index] > arr[i]:
arr[i], arr[lc_index] = arr[lc_index], arr[i]
break
else:
if arr[lc_index] > arr[rc_index]:
arr[i], arr[lc_index] = arr[lc_index], arr[i]
i = lc_index
else:
arr[i], arr[rc_index] = arr[rc_index], arr[i]
i = rc_index
return item
These two functions works fine, but looks pretty cumbersome especially the delete
function, any suggestions how to improve the code?