Beispiel #1
0
static void add_item()
{
    if (sz == MAXSIZE)
        return;

    // find space
    int idx = -1;
    for (int i = 0; i < MAXSIZE; i++) {
        if (vals[i] == -HUGE) {
            idx = i;
            break;
        }
    }
    assert (idx >=0);
    
    // insert
    vals[idx] = randf();
    maxheap_add(h, &vals[idx], vals[idx]);
    sz++;
    
    //    printf("+");
    fflush(NULL);
}
Beispiel #2
0
void exampleMaxHeap()
{
	// Use pooling for efficiency, if you don't want to use pooling
	// then comment out this line.
	pool_maxheap(32);
	
	MaxHeap* H = newMaxHeap(31);
	
	maxheap_add(H, 99, "99");
	maxheap_add(H, 45, "45");
	maxheap_add(H, 57, "57");
	maxheap_add(H, 12, "12");
	maxheap_add(H, 87, "87");
	maxheap_add(H, 42, "42");
	maxheap_add(H, 67, "67");
	
	maxheap_display(H, 2, &toString);

	printf("Pop: '%s'\n", (char*)maxheap_popMax(H));

	maxheap_display(H, 2, &toString);

	printf("Pop: '%s'\n", (char*)maxheap_popMax(H));

	maxheap_display(H, 2, &toString);

	printf("Update 45 to 91\n");
	maxheap_update(H, 45, 91);
	maxheap_set(H, 91, "91");

	maxheap_display(H, 2, &toString);

	printf("Update 91 to 1\n");
	maxheap_update(H, 91, 1);
	maxheap_set(H, 1, "1");
	
	maxheap_display(H, 2, &toString);

	printf("Add 50\n");
	maxheap_add(H, 50, "50");
	
	maxheap_display(H, 2, &toString);

	printf("Pop: '%s'\n", (char*)maxheap_popMax(H));

	maxheap_display(H, 2, &toString);

	printf("Pop: '%s'\n", (char*)maxheap_popMax(H));
	printf("Pop: '%s'\n", (char*)maxheap_popMax(H));
	printf("Pop: '%s'\n", (char*)maxheap_popMax(H));
	printf("Pop: '%s'\n", (char*)maxheap_popMax(H));

	maxheap_display(H, 2, &toString);

	maxheap_clear(H);

	printf("\n");
	// Build a much bigger heap
	int total = 21;
	int keys[] = {0, 23, 3, 6, 41, 17, 21, 8, 9, 68, 2, 1, 34, 29, 38, 11, 15, 16, 45, 65, 39};
	char* items[] = {"0", "23", "3", "6", "41", "17", "21", "8", "9", "68", "2", "1", "34", "29", "38", "11", "15", "16", "45", "65", "39"};

	while (--total >= 0)
		maxheap_add(H, keys[total], items[total]);

	maxheap_display(H, 2, &toString);
	
	printf("Popping.. ");
	while (!maxheap_isEmpty(H))
		printf("%s ", (char*)maxheap_popMax(H));
	printf("\n");

	maxheap_free(H);

	
	// If you're not using pooling this can be commented out. This will
	// free all pooled nodes from memory. Always call this at the end 
	// of using any List.
	unpool_maxheap();
}