mirror of
https://github.com/bkthomps/Containers.git
synced 2025-12-05 15:15:49 +00:00
Make queue trim by factors
Previously, queue would trim every 64 pops. However, this does not make sense for a queue with thousands of elements. Thus, now queue trims every time that the amount of trims times 1.5 is greater or equal to the size of the queue.
This commit is contained in:
@@ -22,7 +22,6 @@
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <memory.h>
|
||||
#include <math.h>
|
||||
#include <errno.h>
|
||||
#include "deque.h"
|
||||
|
||||
@@ -134,6 +133,8 @@ int deque_trim(deque me)
|
||||
free(me->block);
|
||||
me->block = new_block;
|
||||
me->block_count = new_block_count;
|
||||
me->start_index -= start_block * BLOCK_SIZE;
|
||||
me->end_index -= start_block * BLOCK_SIZE;
|
||||
return 0;
|
||||
}
|
||||
|
||||
@@ -171,7 +172,7 @@ int deque_push_front(deque me, void *const data)
|
||||
if (block_index == -1) {
|
||||
const int old_block_count = me->block_count;
|
||||
const int new_block_count =
|
||||
(int) ceil(RESIZE_RATIO * me->block_count);
|
||||
(int) (RESIZE_RATIO * me->block_count) + 1;
|
||||
const int added_blocks = new_block_count - old_block_count;
|
||||
void *temp = realloc(me->block,
|
||||
new_block_count * sizeof(struct node));
|
||||
@@ -221,7 +222,7 @@ int deque_push_back(deque me, void *const data)
|
||||
if (inner_index == 0) {
|
||||
if (block_index == me->block_count) {
|
||||
const int new_block_count =
|
||||
(int) ceil(RESIZE_RATIO * me->block_count);
|
||||
(int) (RESIZE_RATIO * me->block_count) + 1;
|
||||
void *temp = realloc(me->block,
|
||||
new_block_count * sizeof(struct node));
|
||||
if (!temp) {
|
||||
|
||||
@@ -24,7 +24,7 @@
|
||||
#include "deque.h"
|
||||
#include "queue.h"
|
||||
|
||||
static const int TRIM_SIZE = 64;
|
||||
static const double TRIM_RATIO = 1.5;
|
||||
|
||||
struct internal_queue {
|
||||
int trim_count;
|
||||
@@ -131,7 +131,7 @@ int queue_push(queue me, void *const data)
|
||||
bool queue_pop(void *const data, queue me)
|
||||
{
|
||||
me->trim_count++;
|
||||
if (me->trim_count >= TRIM_SIZE) {
|
||||
if (TRIM_RATIO * me->trim_count >= queue_size(me)) {
|
||||
deque_trim(me->deque_data);
|
||||
me->trim_count = 0;
|
||||
}
|
||||
|
||||
13
tst/queue.c
13
tst/queue.c
@@ -39,4 +39,17 @@ void test_queue(void)
|
||||
assert(!queue_back(&get, me));
|
||||
me = queue_destroy(me);
|
||||
assert(!me);
|
||||
me = queue_init(sizeof(int));
|
||||
assert(me);
|
||||
for (int i = 123; i < 123456; i++) {
|
||||
queue_push(me, &i);
|
||||
}
|
||||
const int old_size = queue_size(me);
|
||||
int pop_count = 0;
|
||||
while (!queue_is_empty(me)) {
|
||||
queue_pop(&get, me);
|
||||
pop_count++;
|
||||
}
|
||||
assert(pop_count == old_size);
|
||||
queue_destroy(me);
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user