Beispiel #1
0
/** Hace subir el nodo en index hasta la posicion que le corresponde */
void heap_sift_up(Heap* heap, size_t index)
{
    /* El índice actual del nodo */
    size_t node_i = index;

    /* Repetimos la operacion hasta que se indique lo contrario */
    while(true)
    {
        /* Si el indice es 0, no tiene a donde más subir */
        if(!node_i) break;

        /* Obtenemos el indice del padre de este nodo */
        size_t parent_i = heap_parent_of(node_i);

        /* Si el hijo es mayor que el padre */
        if(heap -> array[node_i].key > heap -> array[parent_i].key)
        {
            /* Se intercambian */
            heap_swap(heap, node_i, parent_i);

            /* Indicamos que cambió el indice y seguimos subiendolo */
            node_i = parent_i;
        }
        /* Si son iguales no hay nada mas que hacer */
        else break;
    }
}
Beispiel #2
0
int
minheap_add (heap_t *heap, elem_t elem)
{
	ofs_t loc, par;

	if (heap->cnt >= HEAP_SIZE)
		return -ENOMEM;

	loc = heap->cnt;
	heap->cnt ++;

	/* place new element in the next spot */
	heap->data[loc] = elem;

	/* while we have a parent move to it and see if order is maintained */
	while ((par = heap_parent_of (heap, loc)) != OFS_INVAL) {

		key_t par_key = elem_key (heap->data[par]);
		key_t loc_key = elem_key (heap->data[loc]);

		/* parent must be smaller */
		if (par_key < loc_key)
			goto done;

		/* if not then swap the elements */
		heap_swap (heap, par, loc);

		/* now move up */
		loc = par;
	}

done:
	return 0;
}