Pseudocode (to implement Algorithm); Loop Invariant 4. (15 pts) There is an algo
ID: 3743344 • Letter: P
Question
Pseudocode (to implement Algorithm); Loop Invariant
4. (15 pts) There is an algorithm called array doubling that is used to increase the size of an array to accommodate new data when an array fills up. In the algorithm, when an array fills up, a new array is created dynamically that is 2x the size of the original, the data is copied to the new array, and the old array is destroyed (a) Write an algorithm to implement an underflow strategy that cuts the array size in half whenever the array falls below half full. (b) Specify the loop invariant in your algorithm. C) Explain how your algorithm maintains the loop invariant.Explanation / Answer
4.
a) Let A be the array and n be the size if the array. m denotes number of elements present in array.
When m becomes less than n/2 we reduce size of array to n/2. As before reducing all elements present first m locations of array we compy those elements by creating a new array of size n/2 and copying those elements to first m locations , then delete the old array.
Algorithm(A,n,m)
1. if(m<n/2)
2.create B[1,2,...n/2]
3. for i=1 to m
4. B[i]= A[i]
5.delete(A)
6. return(B)
b) Here our loop invariant is the m valid elements ocupy first m locations of the array.
c) Before resizing all m valid elements are first locations of the array and after resizing also all m
valid elements ocupy first m locations of new array.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.