Question: In JAVA, create a program with 2 methods: You are given an array whose size is an even number, and you are to switch the
In JAVA, create a program with 2 methods: You are given an array whose size is an even number, and you are to switch the first and the second half. For example, if the array contains the eight numbers
{9, 13, 21, 4, 11, 7, 1, 3} then you should change it to
{11, 7, 1, 3, 9, 13, 21, 4} In the main() method, initialize the input array using the array initializer, i.e.,
int[] values = {9, 13, 21, 4, 11, 7, 1, 3}; then implement the pseudocode below
i = 0 j = size/2 While(i< size/2) Swap elements at positions i and j i++ j++
In a separate method
public static void swap(int[] a, int i, int j)
implement the algorithm to swap element a[i] and a[j].
Then Write the comments for swap() in the correct format.
Here is the code I have but there is a OutOfBounds error:
public class SwapHalves {
public static void main (String[] args) {
int[] values = {2, 4, 6, 8, 10, 12, 14, 16};
int currentSize = values.length;
currentSize = currentSize - 1;
int i = 0;
int j = currentSize / 2;
while (i < j) {
swap(values, i, j);
i++;
j++;
}
System.out.print(values[i]);
}
public static void swap(int[] a, int i, int j) {
int temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
Step by Step Solution
There are 3 Steps involved in it
Get step-by-step solutions from verified subject matter experts
