Пример #1
0
STATIC void heap_siftup(mp_obj_list_t *heap, mp_uint_t pos) {
    mp_uint_t start_pos = pos;
    mp_uint_t end_pos = heap->len;
    mp_obj_t item = heap->items[pos];
    for (mp_uint_t child_pos = 2 * pos + 1; child_pos < end_pos; child_pos = 2 * pos + 1) {
        // choose right child if it's <= left child
        if (child_pos + 1 < end_pos && mp_binary_op(MP_BINARY_OP_LESS, heap->items[child_pos], heap->items[child_pos + 1]) == mp_const_false) {
            child_pos += 1;
        }
        // bubble up the smaller child
        heap->items[pos] = heap->items[child_pos];
        pos = child_pos;
    }
    heap->items[pos] = item;
    heap_siftdown(heap, start_pos, pos);
}
Пример #2
0
void *heap_remove(heap_t *h, int k) {
    void *data;

    if (k >= h->len) {
        return NULL;
    }

    data = h->data[k];
    --h->len;
    heap_set(h, k, h->data[h->len]);
    heap_siftdown(h, k);
    heap_siftup(h, k);
    if (h->record) {
        h->record(data, -1);
    }
    return data;
}
Пример #3
0
/* heap_insert insert `data' into heap `h' according
 * to h->less.
 * 0 returned on success, otherwise -1. */
int heap_insert(heap_t *h, void *data) {
    int k;

    if (h->len >= h->cap) {
        void **ndata;
        int ncap = (h->len + 1) * 2; /* callocate twice what we need */

        ndata = realloc(h->data, sizeof(void*) * ncap);
        if (!ndata) {
            return -1;
        }
        h->data = ndata;
        h->cap = ncap;
    }
    k = h->len;
    ++h->len;
    heap_set(h, k, data);
    heap_siftdown(h, k);
    return 0;
}
Пример #4
0
STATIC mp_obj_t mod_uheapq_heappush(mp_obj_t heap_in, mp_obj_t item) {
    mp_obj_list_t *heap = get_heap(heap_in);
    mp_obj_list_append(heap_in, item);
    heap_siftdown(heap, 0, heap->len - 1);
    return mp_const_none;
}