Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

In JAVA, create a program with 2 methods: You are given an array whose size is a

ID: 3738060 • Letter: I

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 first and the second half. For example, if the array contains the eight numbers

then you should change it to

In the main() method, initialize the input array using the array initializer, i.e.,

then implement the pseudocode below

In a separate method

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;

   }

}

Explanation / Answer

/*If you have any query do comment in the comment section else like the solution*/

The problem was in your length function instead of 8 it was returning 7 and the second problem was your while condition initial value of i =0 and j=4 and you were incrementing both in each iteration so i will be always lesser than j and the loop will go into infinite loop and will produce ArrayIndexOutOfBound error when j reaches maximum value that is length of array.

public class SwapHalves
{
public static void main (String[] args)
{
int[] values = {2, 4, 6, 8, 10, 12, 14, 16};
int currentSize = values.length+1;
currentSize = currentSize - 1;
int i = 0;
int j = (currentSize/2);
while (j<currentSize)
{
swap(values, i, j);
i++;
j++;
}
for(i=0;i<values.length;i++)
System.out.print(values[i]+" ");
}   

//Function for swaping two values
public static void swap(int[] a, int i, int j)
{
int temp = a[i];
a[i] = a[j];
a[j] = temp;

}
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote