if left(in /no children return elseif right(in /only left child if heap[iheap[left( )swap heap[iand heap[left( )else /two children if heap[left( )heap[right( )and heap[iheap[left( )swap heap[iand heap[left( )bubbledown(left( ),heap,nelseif heap[iheap[right( )swap heap[iand heap[right( )bubbledown(right( ),heap,nin the same way that the insert algorithm does not increment the heap sizethis delete algorithm does not decrement the heap size that has to be done separately by whatever algorithm calls it note also that this algorithm does not attempt to be fair in the sense that if two or more nodes have the same priorityit is not necessarily the one that has been waiting longest that will be removed first howeverthis factor could easily be fixedif requiredby keeping track of arrival times and using that in cases of equal priority as with insertiondeletion takes at most (log nstepsbecause the maximum number of times it may have to bubble down or bubble up the replacement element is the height of the tree which is log building new heap tree from scratch sometimes one is given whole set of new items in one goand there is need to build binary heap tree containing them in other wordswe have set of items that we wish to heapify one obvious possibility would be to insert the items one by one into heap treestarting from an empty treeusing the (log 'bubble upbased insert algorithm discussed earlier that would clearly have overall time complexity of (nlog nit turns outhoweverthat rearranging an array of items into heap tree form can be done more efficiently using 'bubble downfirst note thatif we have the items in an array in positions nthen all the items with an index greater than / will be leavesand not need bubbling down thereforeif we just bubble down all the non-leaf items [ / ] [ by exchanging them with the larger of their children until they either are positioned at leafor until their children are both smallerwe obtain valid heap tree consider simple example array if items from which heap tree must be built we can start by simply drawing the array as treeand see that the last entries (those with indices greater than / are leaves of the treeas follows