when I coding, it shows my grade is 9/100 because size should be 11 after 10 thi
ID: 3589693 • Letter: W
Question
when I coding, it shows my grade is 9/100 because size should be 11 after 10 things and prepend but instead of 10.
CS 143 Assignment 1 IntArray With Prepend DUE on Monday, October 9 at 11:59 PM In class, we implemented an IntArray class which internally had an array of integers but ENHANCEd it by making it easy to add new elements to the end. We saw that adding n elements to an IntArray would only take O(n) time. It accomplished this by doubling the underlying size of the array and copying the old array every time it ran out of space. If n total elements are added to the array, in the worst case, the array might have run out of space and had to copy itself when the very last (nth) element was added, when thend element was added, th,th and so on down to the starting size of the array. Every time the array runs out of space, it needs to copy all the elements from the old array to the new array. However, even as n becomes very large and this series becomes arbitrarily long, nExplanation / Answer
Hi,
To prepend the array, you have to move all the element to the right by 1, here there are 2 cases, if length is more than existing length or less than, if its more, we need to expand the array and move everything to the right, if not, we just move everything to right and add to start, here is the code you can use, public void prepend(int x){
if(length>=a.length)
{
int[] b=new int[a.length*2];
for(int i=0;i<a.length;i++)
{
b[i+1]=a[i];//setting values in new array starting from 1
}
a=b;
a[0]=x;//setting value at start
length=length+1; //increasing length
}
else
{
for(int i=a.length-1;i>=0;i--)
{
a[i+1]=a[i];//shifting everything to right by 1
}
a[0]=x;//setting value at start
length=length+1; //increasing length
}
}
Thumbs up if this was helpful, otherwise let me know in comments
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.