swapping two numbers in array in java code example

Example: swap chunks of array in java

import java.util.Arrays;

// ... //

int[] digits = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };

// Rotate is a fancy way to say split around an index, and swap the chunks
// For the comments, assume `A=digits`
int[] rotate(int[] A, int r) {
  int N = A.length; // total number of elements
  
  // Arrays.copyOfRange(array, start, end) will return array[start:end),
  // where start is inclusive and end exclusive
  int[] left = Arrays.copyOfRange(A, 0, r); // [0,1,...,r-1], so r=3->[0,1,2]
  int[] right = Arrays.copyOfRange(A, r, N); // [r,r+1,...,N-1], so r=7->[7,8,9]
  
  // Now, concatenate right with left and store in result
  // - in JS this would be `result=[...right, ...left]`
  int[] result = new int[N];
  int R = N - r; // length of right array
  for(int i=0; i<N; ++i) {
    // ternary expression: same as
    //   `if(i<R) result[i] = right[i];`
    //   `else    result[i] = left[i-R];`
    result[i] = i<R ? right[i] : left[i-R];
  }
  
  return result;
}

Tags:

Java Example