Home > database >  Java Shifting the Elements Multiple Times
Java Shifting the Elements Multiple Times

Time:09-27

I want to shift my elements in the array multiple times:

for example: Old array: (1,2,3 ,4 5) shift 3 steps New array: (3, 4, 5, 1, 2)

I created this function but it only shifts 1 step:

public static int[] shiftmultiple(int[] array1, int shiftCount) {
    int[] array2 = new int[array1.length];
    
    for(int i = 0; i < shiftCount; i  ){
        for(int j = 0; j < array1.length-1; j  ){
            array2[j 1] = array1[j];
        }
        array2[0] = array1[array1.length-1];
    }
    
    return array2;
}

P.S. I need to make new array since that is the required instruction.

CodePudding user response:

Ask yourself what array2 is filled at i with at what index in array.

for (int i = 0; i < array.length; i  ) {
    int j = ... i ... shiftCount ...;
    array2[i] = array[j];
}

For shiftCount 0, j = i;. What for 1, 2, 3?

Useful is the modulo operator % or an if statement for starting at 0 again.

shiftCount i 0 1 2 3 4
0 j 0 1 2 3 4
1 j 1 2 3 4 0
2 j 2 3 4 0 1
3 j 3 4 0 1 2

CodePudding user response:

Your approach might work, except that you create array2 from the contents of array1, then repeat the process (creating array2 from array1). Overwriting the same information instead of taking the previous answer and working from there.

However your solution is quite inefficient (even once fixed) requiring scanning through the entire array each time you shift. Can I recommend you look at the modulus (%) operator instead? Using this you can assign everything with a single pass.

  • Related