Download as txt, pdf, or txt
Download as txt, pdf, or txt
You are on page 1of 1

C-7.29 Revise the array list implementation given in Section 7.2.

1 so that when the


ac#tual number of elements, n, in the array goes below N/4, where N is the array
capacity, the array shrinks to half its size

public E remove(int index) {

E removedElement = data[index];
for (int i = index; i < size - 1; i++)
data[i] = data[i + 1];
data[size - 1] = null;
size--;
if (size < data.length/4)
resize(data.length / 2);
return removedElement;
}

-----------------------------------------------------------------------------------
------------------

C-7.31 Give a formal proof that any sequence of n push or pop operations (that is,
in#sertions or deletions at the end) on an initially empty dynamic array takes
O(n)time, if using the strategy described in Exercise C-7.29

In the given proof, we establish that any sequence of n push or pop operations on
an initially empty dynamic array, using the resizing strategy described in Exercise
C-7.29, takes O(n) time. This is because for each push operation, if resizing is
required, it takes O(n) time to resize the array to double its size, copy the
elements, and add the new element. Similarly, for each pop operation, if resizing
is required, it takes O(n) time to resize the array to half its size, copy the
elements (excluding the last one), and remove the last element. Thus, considering
the worst-case scenario for each operation, the overall time complexity of the
sequence of n operations is O(n), ensuring efficient performance.

-----------------------------------------------------------------------------------
------------------
C-7.32 Consider a variant of Exercise C-7.29, in which an array of capacity N is
resized to capacity precisely that of the number of elements, any time the number
of elements in the array goes strictly below N/4. Give a formal proof that any
sequence of n push or pop operations on an initially empty dynamic array takes O(n)
time.

Each push or pop operation may trigger a resize, which copies all n elements to a
new array in worst-case scenarios. However, since resizing occurs only when the
number of elements reaches the N/4 threshold, the number of resize operations is
limited. Thus, considering the worst-case scenarios and the reduced frequency of
resize operations, the overall time complexity remains O(n). For each pop
operation, if resizing is required, the resizing process again takes O(n) time, as
all n elements need to be copied to the new array. Similar to the push operation,
the resizing occurs only when the number of elements goes below N/4.

You might also like