void *minheap_remove(struct minheap *heap) { assert(heap != NULL); assert(heap->size > 0); void *min = heap->values[0]; heap->values[0] = heap->values[heap->size-1]; --heap->size; // reallocate when too much capacity if (heap->size <= heap->capacity/2) { int new_capacity = heap->capacity/2; void **new_values = (void**)realloc(heap->values, new_capacity*sizeof(void*)); if (new_capacity == 0) heap->values = NULL; else heap->values = new_values; heap->capacity = new_capacity; } int cur_idx = 0; int swap_idx = minheap_get_swap_idx(heap, cur_idx); while (swap_idx > 0) { utils_swap(&heap->values[cur_idx], &heap->values[swap_idx]); cur_idx = swap_idx; swap_idx = minheap_get_swap_idx(heap, cur_idx); } return min; }
int utils_permute_inverse(bmp_byte_t *pixels, size_t size, bmp_word_t seed) { int *rand_numbers = utils_generate_rand_numbers(size, seed); if (rand_numbers == NULL) { return -1; } int i; for (i = 0; i < size; i++) { utils_swap(pixels, i, rand_numbers[size - 1 - i]); } free(rand_numbers); return 0; }
int minheap_add(struct minheap *heap, void *value) { assert(heap != NULL); // empty heap if (heap->size == 0) { assert(heap->values == NULL); assert(heap->capacity == 0); void **values = (void**)malloc(sizeof(void*)); if (values == NULL) return -1; values[0] = value; heap->values = values; heap->size = 1; heap->capacity = 1; return 0; } // heap is at capacity, double capacity if (heap->size == heap->capacity) { int new_capacity = heap->capacity*2; void **new_values = (void**)realloc(heap->values, sizeof(void*)*new_capacity); if (new_values == NULL) return -1; heap->values = new_values; heap->capacity = new_capacity; } heap->values[heap->size] = value; ++heap->size; int cur_pos = heap->size-1; int par_pos = (cur_pos-1)/2; while (heap->cmp(heap->values[cur_pos], heap->values[par_pos]) == -1 && par_pos >= 0) { utils_swap(&heap->values[cur_pos], &heap->values[par_pos]); cur_pos = par_pos; par_pos = (par_pos-1)/2; } return 0; }