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


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]

Sharon Christine
Sharon Christine

An investment in knowledge pays the best interest

Updated on: 19-Feb-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements