Question: Our implementation of insert for the DynamicArray class, as given in Code Fragment 5.5, has the following inefficiency. In the case when a re- size

Our implementation of insert for the DynamicArray class, as given in Code Fragment 5.5, has the following inefficiency. In the case when a re- size 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.

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: self. resize(2 self. capacity)

for j in range(self. n, k, 1): self. A[j] = self. A[j1]

self. A[k] = value self. n += 1

# not enough room # so double capacity # shift rightmost first

# store newest element

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

By Python

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!