a) Write a method in Java or Python/pseudo-code that reverses the contents of an
ID: 3755386 • Letter: A
Question
a) Write a method in Java or Python/pseudo-code that reverses the contents of an ArrayList, in place ublic void reve rse În place (final ArrayList list) { } This means that you cannot copy the contents of the arraylist to another arraylist or an array and then try to manipulate it. In other words, you are not allowed to use another data tructure that stores the contents of the given arraylist) Example: given an arraylist A [3 69 2 10 22], after applying reverseInPlace to it, it will contain A-122 10 29 6 3 Make sure to handle the cases when the array list is empty or if it has a single value. Also, as the very first step, make sure the list is non-null (otherwise throw an IllegalArgumentException). int: you will find these methods usefui: public E set (int index, E element) Used to set an element in an ArrayList object at the specified index. public E get (int index) Replaces the element at the specified position in this list with the specified element. ) What is the time-complexity of your reverselnPlace method? ) Write a meaningful test method for a list containing three different elements: Test public void testReverseInPlace30 .. 1 Maximum number of characters (including HTML tags added by text editor): 32,000Explanation / Answer
answer a)
==========
public void reverseInPlace(final ArrayList<Integer> list){
if(list == null)
throw new IllegalArgumentException();
int i = 0, j = list.size() - 1;
int temp;
for(; i < j; i++, j--){
temp = list.get(i);
list.set(i, list.get(j));
list.set(j, temp);
}
}
answer b)
==========
The algorithm is of O(n)
answer c)
=========
@Test
public void testReverseInPlace3(){
ArrayList<Integer> list = new ArrayList<Integer>();
list.add(2);
list.add(4);
list.add(6);
reverseInPlace(list);
Integer[] expected = {6, 4, 2};
for(int i = 0; i < expected.length; i++)
assertEquals( expected[i], list.get(i));
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.