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
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started