deleting process in heap
deleting process in heap
Heap insertion
Heap Structure:
Simple index calculations allow navigation through the tree:
- left child of Item at index i is located at 2i
- right child of Item at index i is located at 2i+1
- parent of Item at index i is located at i/2
Heap Inserting:
Insertion is a two-step process
- Add new element at next available position on bottom row (but this might violate heap property; new value larger than parent)
- Reorganise vales along path to root to restore heap property
Complexity: O(log(n))
HeapInsert(Heap h, Item it):
// is there space in the array?
assert(h->nitems < h->nslots)
h->nitems++
// add new item at end of array
h->items[h->nitems] = it
// move new item to its correct place
fixUp(h->items, h->nitems)
// force value at a[i] into correct position
void fixUp(Item a[], int i)
while (i > 1 && less(a[i/2], a[i])):
swap(a, i, i/2)
i = i / 2; // integer division
Heap Deleting:
Deletion is a three-step process:
- Replace root (always root) value by bottom-most, rightmost value
- Remove bottom-most, rightmost value
- Reorganise values along path from root to restore heap
Complexity: O(log(n))
(12)
time complexity comparison
(12)