1. Write the method swap that takes in an array of type int and two integers, index1 and index2. The result of calling swap is that the elements at positions index1 and index2 swapped. swap returns no value.
Example:
int[] nums = { 3, 9, 1, 8, 7, 2, 4 }; swap(nums, 1, 4); // the 9 and the 7 swap positions // nums now contains { 3, 7, 1, 8, 9, 2, 4 }
Here is a small bit of code to get you started.
public void swap(int[] arr, int index1, int index2) { int temp = arr[index1]; // you figure out the rest. }
2. Write the method reverse that takes an array of ints as its input and modifies the array so that its elements are reversed.
Example:
int[] nums = { 3, 9, 1, 8, 7, 2, 4 }; reverse(nums); // nums now contains { 4, 2, 7, 8, 1, 9, 3 };
Write reverse. Hint: swap is very useful in solving this problem.
3. Write swap and reverse for ArrayList<Integer>.