Question: In each Python file, please also include code for testing your functions. Our implementation of insert for the DynamicArray class, as given in Code Fragment

In each Python file, please also include code for testing your functions.

Our implementation of insert for the DynamicArray class, as given in Code Fragment 5.5, 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.

Hint You are going to need two (non-nested) loops.

Note: Create a method insert_new in the DynamicArray class. In your test code, set the number of insert operations N= 10000000. Compare the amortized time for adding a new item to the middle of a dynamic array with the insert and insert_new methods. (Refer to Code Fragment 5.4 for how to measure the amortized time for a specific operation.) A suggested output for the test code: N insert insert_new 10000000 _______ __________

Code Fragment 5.5: Implementation of insert for our DynamicArray class.

def insert(self, k, value): Insert value at index k, shifting subsequent values rightward.

# (for simplicity, we assume 0 <= k <= n in this verion)

if self. n == self._capacity: # not enough room

self. resize(2* self. capacity) # so double capacity

for j in range(self. _n, k, 1): # shift rightmost first

self._A[j] = self._A[j1]

self. _A[k] + = value #store newest element

self._n += 1

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!