Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Amortized Analysis II #25

Closed
hamidgasmi opened this issue Feb 18, 2020 · 1 comment
Closed

Amortized Analysis II #25

hamidgasmi opened this issue Feb 18, 2020 · 1 comment
Assignees

Comments

@hamidgasmi
Copy link
Owner

Let's imagine we add support to our dynamic array for a new operation PopBack (which removes the last element). PopBack will reallocate the dynamically-allocated array if the size is ≤ the capacity / 2 to a new array of half the capacity. So, for example, if, before a PopBack the size were 5 and the capacity were 8, then after the PopBack, the size would be 4 and the capacity would be 4.

Give an example of n operations starting from an empty array that require O(n2) copies.

@hamidgasmi
Copy link
Owner Author

Answer:

Let n be a power of 2.
Add n/2 elements, then alternate n/4 times between doing a PushBack of an element and a PopBack.

Explanation:
Once we have added n/2 elements, the dynamically-allocated array is full (size=n/2, capacity=n/2). When we add one element, we resize, and copy n/2 elements (now: size = n/2+1, capacity=n)
When we then remove an element (with PopBack), we reallocate the dynamically allocated array and copy n/2 elements. So, each of the final n/2 operations costs n/2 copies, for a total of n2/4 moves, or O(n^2)

# for free to join this conversation on GitHub. Already have an account? # to comment
Projects
None yet
Development

No branches or pull requests

1 participant