/** returns the index of the maximum node between father and sons * * @param father - father index * * @return index of the maximum node */ inline uint64_t max_father_children( uint64_t father ) { uint64_t sx = father, dx; sx = dx = left_node( father ); if(dx + 1 < heap_size) dx++; if(heap_t[dx].value > heap_t[sx].value) sx = dx; if(heap_t[father].value > heap_t[sx].value) sx = father; return sx; }
static void max_heapify(heap_t heap, unsigned long i) { for (;;) { unsigned long l = left_node(i), r = right_node(i), max; max = l <= heap->curr && heap->cmp(heap_get(heap, l), heap_get(heap, i)) > 0 ? l : i; if (r <= heap->curr && heap->cmp(heap_get(heap, r), heap_get(heap, max)) > 0) max = r; if (max == i) break; heap_swap(heap, i, max); i = max; } }
/** reorganize the heap * * @param i - index from which the reorganization start */ inline void reorganize_heap( uint64_t i ) { uint64_t select; // checks if some node must be put to the top while(i > 0 && (heap_t[i].value > heap_t[father( i )].value)){ swap( &heap_t[i], &heap_t[father( i )] ); i = father( i ); } // checks if some node must be put on the bottom while(left_node( i ) < heap_size && i != max_father_children( i )){ select = max_father_children( i ); swap( &heap_t[i], &heap_t[select] ); i = select; } }
void max_heapify(Heap h, unsigned int idx){ unsigned int l = 0 ,r = 0, sz = 0, largest = 0; l = left_node(idx); r = right_node(idx); sz = heap_size(h); largest = idx; if (l <= sz && h[l].val > h[idx].val){ largest = l; } if (r <= sz && h[r].val > h[largest].val){ largest = r; } if (largest != idx){ Hnode temp; temp = h[idx]; h[idx] = h[largest]; h[largest] = temp; max_heapify(h, largest); } }
int ast_heap_verify(struct ast_heap *h) { unsigned int i; for (i = 1; i <= (h->cur_len / 2); i++) { int l = left_node(i); int r = right_node(i); if (l <= h->cur_len) { if (h->cmp_fn(heap_get(h, i), heap_get(h, l)) < 0) { return -1; } } if (r <= h->cur_len) { if (h->cmp_fn(heap_get(h, i), heap_get(h, r)) < 0) { return -1; } } } return 0; }