I am trying to do the circular left shift of an array by n positions using only a single 1D array. I can do it in two arrays, but I haven\'t figured out how to do it using o
I do belive that System.arraycopy would actually just take all your data from one array, and put it into another one of the same length just shifted.
Anyways thinking about that problem is a quite interesting task. The only Solution i could think about right now is to shit it one by one. Without using another Array it would look like that:
for(int i = 0; i < shift;i++)
{
tmp = array[0];
for(int j = 0;j
for Arrays greater than 30 items it is but more efficient to use this:
for (int i = 0; i < shift; i++) {
tmp = array[0];
System.arraycopy( array, 1, array, 0, array.length - 1 );
array[array.length - 1] = tmp;
}
But for large arrays and great shift that are close to the array size aswell as for short arrays and small shifts this method wins the race:
int[] array2 = new int[shift];
for (int i = 0; i < shift; i++)
{
array2[i] = array[i];
}
System.arraycopy(array, shift, array, 0, array.length - shift);
for (int i = array.length - shift; i < array.length; i++)
{
array[i] = array2[shift + i - array.length];
}
Ive tested that with a few array sizes and shifts Here are the results for
int[] array = new int[100000];
int shift = 99999;
in nanoseconds: 1st method:5663109208 2nd method:4047735536 3rd method:6085690 So you should really use the 3rd method. Hope that helps