/* heap_insert -- insère un nouvel élément dans le tas. * La valeur de retour indique si l'insertion s'est bien passée. * Complexité: O(ln(heap_size(h))) */ int heap_insert(Heap *h, void *item) { assert((h != NULL) && (h->tab != NULL) && (item != NULL)); if (heap_size(h) == heap_max_size(h)) return 0; h->tab[h->size++] = item; heap_shift_up(h, h->size-1); return 1; }
Heap *heap_union(Heap *H1, Heap *H2, int free_keys) { //can probably be better Heap *H = malloc(sizeof(Heap)); H->comparator = H1->comparator; //assume same as H2 H->size = H1->size + H2->size; H->h_size = (1 << (int)floor(log2(H->size))+1); //next closest 2^n H->arr = malloc(sizeof(void *) * H->h_size); int i = 0; for(; i < H1->size; i++) { H->arr[i] = H1->arr[i]; heap_shift_up(H, i); } for(i = 0; i < H2->size; i++) { H->arr[H1->size+i] = H2->arr[i]; heap_shift_up(H, H1->size+i); } if(free_keys) { //join 2 heaps, preserving(merge; 0)/destroying(meld; 1) the original heaps. for(i = 0; i < H1->size; i++) { free(H1->arr[i]); } for(i = 0; i < H2->size; i++) { free(H2->arr[i]); } } return H; }
Heap *heapify(void *arr[], int size, int (*comparator)(void * key1, void *key2)) { Heap *H = malloc(sizeof(Heap)); H->comparator = comparator; H->size = size; H->h_size = (1 << (int)floor(log2(size))+1); //next closest 2^n H->arr = malloc(sizeof(void *) * H->h_size); for(size = 0; size < H->size; size++) { H->arr[size] = arr[size]; heap_shift_up(H, size); } return H; }
Heap *heap_push(Heap *H, void *key) { if(H->size == H->h_size) { H->arr = realloc(H->arr, (sizeof(void *) * (H->h_size *= 2))); } H->arr[H->size] = key; return heap_shift_up(H, H->size++); }