-5

Need to reverse an array of integers based on the input number For example :

Array be [1,2,3,4,5,6,7,8,9] and value of subset be N = 4
then the array after reversal will be [4, 3, 2, 1, 8, 7, 6, 5, 9].
if N = 3 then output should be [3,2,1,6,5,4,9,8,7]

Couldn't think of a proper logic with recursive method or with any looping concepts

SurajSr
  • 141
  • 10

1 Answers1

1

Try below java code

public static int[] reverse(int[] a, int number) {
    // negative case
    if (number < 0) {
        return a;
    }
    // higher count than array length
    int size = number < a.length ? number : a.length;
    int[] b = new int[size];
    System.arraycopy(a, 0, b, 0, size);
    for (int i = b.length - 1; i >= 0; i--) {
        a[b.length - 1 - i] = b[i];
    }
    return a;
}

Array has index with each element so above loop code is simple and efficient.

Sagar balai
  • 479
  • 6
  • 13