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

I am trying to reverse an array at certain indexes eg:Example: Array = [ 1,2,3,4

ID: 3693695 • Letter: I

Question

I am trying to reverse an array at certain indexes eg:Example: Array = [ 1,2,3,4,5,6,7,8 ] * reverse(3,6) results in * Array = [ 1,2,3,7,6,5,4,8 ] Below are the methods i already have. But there is something wrong with my reverse method. Can someone please adjust it so it will work for an example like above?

public boolean reverse(int start, int end)

for (int i = start; i < start + (start + end)/2; i++){ swap (i , end - i); }

return true; }

public boolean swap(int index1, int index2)

int temp = myArray[index1]; myArray[index1] = myArray[index2]; myArray[index2] = temp; return true; }

Explanation / Answer

Answer:

Hi, I have modified your code. It is working fine now. I have commented out the for loop which is not needed for your requirement. Please note that in sample output you mentioned line 1,2,3,7,6,5,4,8 but it should be 1,2, 3, 7, 5, 6, 4, 8

public boolean reverse(int start, int end) {
   //for (int i = start; i < start + (start + end)/2; i++){
   
   swap (start , end);
   //   }
  

   return true;
   }
     
    public boolean swap(int index1, int index2){
   
int temp = myArray[index1];
   myArray[index1] =   myArray[index2];
   myArray[index2] = temp;
   return true;
   }

----------------------------------------------------------------------------------

Please find the below test program for above swap functionality

TestTest.java


public class TestTest {

   /**
   * @param args
   */
   static int myArray[] ={1,2,3,4,5,6,7,8};
   public static void main(String[] args) {
      
       reverse(3, 6);
       for(int i=0; i<myArray.length; i++){
           System.out.print(myArray[i] +" ");
       }
   }
   public static boolean reverse(int start, int end) {
   //for (int i = start; i < start + (start + end)/2; i++){
       swap (start , end);
   //   }
  
   return true;
   }
     
   public static boolean swap(int index1, int index2){
   int temp = myArray[index1];
   myArray[index1] =   myArray[index2];
   myArray[index2] = temp;
   return true;
   }
}

Output:

1 2 3 7 5 6 4 8

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