The folllwing code is in python, but I will highlight the lines that do the heavy lifting, and in the process hopefully present a different solution of creating a min-heap
heapArray = []
for heapKey in someArray:
insert(heapArray, int(heapKey))
return heapArray;
def insert(heapArray, heapKey):
heapArray.append(heapKey)
index_of_key = len(heapArray)-1
parent_index_of_key = (index_of_heap_key-1)/2
while index_of_key>0:
if(heapKey < heapArray[parent_index_of_key]):
__swap(index_of_key, parent_index_of_key, heapArray)
index_of_key = parent_index_of_key;
parent_index_of_key = (index_of_key-1)/2
else:
break # we have reached the right spot
In the above example, we re-create the heap (yes that means more memory, but for illustration purposes this maybe a good start). As we create the heap, we simply check the value of the newly inserted key with its parent (via parent_index_of_key).
If the parent is larger than its child, then we swap the value and update the indexes (both for the swapped key and its new parent). We repeat that process until we have either reached the top of the heap or if the heap key can't go any further up the chain
The in-place swaps are clearly more efficient, but the above is more intuitive and easy to follow. Clearly, I won't use the above code, where memory is a large constraint, but would consider it for cases where code conciseness and clarity trump memory utilization.