0

I want to perform a circular left shift in an array between index i and index j (both inclusive).

For example : Consider array A such as,

int[] A = {1, 2, 3, 4, 5};

If I want to perform circular left shift in the given array A between 0 (index i) and 2 (index j), the output is :

A = {2, 3, 1, 4, 5}

Is there any inbuilt function in java that can perform this type of operation.

I'm not asking about how to circular left shift an array n times. My question is to circular left shift some of the elements within an array as I have showed through the example.

meisner97
  • 9
  • 6

2 Answers2

1

Yes there is a builtin function for it: Collections.rotate

For example,

Collections.rotate(Arrays.asList(A).subList(i, j+1), -1);

Update:

This does not work directly for primitive arrays because Arrays.asList does not do boxing for you. You need to create an Integer[] or List<Integer> somehow, which does not have very elegant way to do.

lnyng
  • 925
  • 6
  • 18
  • This function is giving out of bounds exception when used on integer array but works fine on a string array – meisner97 Mar 13 '19 at 18:19
  • @meisner97 This is because `Arrays.asList` does not work for primitive type arrays. See https://stackoverflow.com/questions/1073919/how-to-convert-int-into-listinteger-in-java. – lnyng Mar 13 '19 at 20:28
0

For collections there are numerous manipulations available. For arrays the class Arrays provides copyOfRange and other methods, but nothing for an in-situ operation as desired. You can do:

int[] a = {1, 2, 3, 4, 5};
final int lwb = 0;
final int upb = 2;

with a lambda:

int alwb = a[lwb];
Arrays.setAll(a, i -> 
    i < lwb || i > upb ? a[i]
    i < upb -> a[i+1] : alwb
);

Or best:

int alwb = a[lwb];
System.arraycopy(a, lwb + 1, a, lwb, upb - lwb - 1);
a[upb] = alwb;
Joop Eggen
  • 107,315
  • 7
  • 83
  • 138