How to move an element of an array to a specific position (swap)?

Java 8Object Oriented ProgrammingProgramming

To move an element from one position to other (swap) you need to –

  • Create a temp variable and assign the value of the original position to it.
  • Now, assign the value in the new position to original position.
  • Finally, assign the value in the temp to the new position.

Example

Live Demo

import java.util.Arrays;
public class ChangingPositions {
   public static void main(String args[]) {
      int originalPosition = 1;
      int newPosition = 1;
      int [] myArray = {23, 93, 56, 92, 39};
      int temp = myArray[originalPosition];
     
      myArray[originalPosition] = myArray[newPosition];
      myArray[newPosition] = temp;
      System.out.println(Arrays.toString(myArray));
   }
}

Output

[23, 39, 56, 92, 93]
raja
Published on 08-Jan-2018 16:42:34
Advertisements