Our implementation of insert for the DynamicArray class, as given in Code Fragme
ID: 3601162 • Letter: O
Question
Our implementation of insert for the DynamicArray class, as given in Code Fragment above has the following inefficiency. In the case when a resize occurs, the resize operation takes time to copy all the elements from an old array to a new array, and then the subsequent loop in the body of insert shifts many of those elements. Give an improved implementation of the insert method, so that, in the case of a resize, the elements are shifted into their final position during that operation, thereby avoiding the subsequent shifting.
import ctypes # provides low-level arrays class DynamicArray: """A dynamic array class akin to a simplified Python list.""" def _init__(self): "" "Create an empty array.""" self. n = 0 self-capacity = 1 self. Aself. make array (self. capacity) # count actual elements # default array capacity # low-level array def len (self) """Return number of elements stored in the array.""" return self. n def _getitem_ _(self, k): """Return element at index k.""" if not 0Explanation / Answer
resize function can be modified as follows which can be called in modified
insert function:
def _resize(elf,c,i):
B = self._make_array(c)
for k in range(sel._n):
if (k < i):
B[k] = self._A[k]
else:
B[k+1] = self._A[k]
self._A = B
self._capacity = c
Now insert function will be calling resize(2* self._capacity, k) and returning
from that function, it can directly use the k index to fill the value as shifting
has already been done in the resize function while copying.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.