Write two public static methods in the U6_L4_Activity_Two class. The first should have the signature swap(int[] arr, int i, int j) and return type void. This method should swap the values at the indices i and j of the array arr (precondition: i and j are both valid indices for arr). The second method should have the signature allSwap(int[] arr) and return type void. The precondition for this method is that arr has an even length. The method should swap the values of all adjacent pairs of elements in the array, so that for example the array {3, 5, 2, 1, 8, 10} becomes {5, 3, 1, 2, 10, 8} after this method is called.

Respuesta :

Answer:

public static void swap(int[] arr, int i, int j) {

   if(i >=0 && i <=arr.length-1 && j >=0 && j<=arr.length-1){

       int hold = arr[i];

       arr[i] = arr[j];

       arr[j] = hold;

   }

}

public static void allSwap(int[] arr) {

   if (arr.length % 2 == 0){

       for(int i=0; i<arr.length; i+=2){

           int hold = arr[i+1];

           arr[i+1] = arr[i];

           arr[i] = hold;

       }

   } else{

       System.out.println("array length is not even.");

   }

}

Explanation:

The two functions, swap and allSwap are defined methods in a class. The latter swaps the item values at the specified index in an array while the second accepts an array of even length and swap the adjacent values.