-
Notifications
You must be signed in to change notification settings - Fork 0
Description
The following implementation would turn out to be inefficient in cases where you need to push several elements into the list frequently, since you need to reallocate the memory at every push.
void push(struct ArrayList *arraylist, int el)
{
arraylist->elements = realloc(arraylist->elements, arraylist->length * sizeof(int));
arraylist->elements[arraylist->length] = el;
arraylist->length++;
}
Solution:
It would be more efficient to allocate more memory at the beginning, and then push into the data structure into those preallocated memory blocks. Once you hit the capacity, reallocate the list to become double the size it currently is.
For this you could add another field called capacity in the data structure that denotes the current capacity (not necessarily equal to the number of elements present in the list) of the list. When the number of elements in the list become equal to capacity - 1, reallocate the list to now have capacity = capacity * 2.
This would lead to better ammortized time complexity.