circular left shift of an array by n positions in java

前端 未结 12 2376
醉梦人生
醉梦人生 2020-12-31 20:16

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

12条回答
  •  情书的邮戳
    2020-12-31 21:06

    I would shift it 1 element at a time in place, using a single temporary variable to hold the element while moving elements 1 place along each. I would then repeat this n times to achieve n shifts.

    public static void main( String[] args ) {
        int[] array = {1,2,3,4,5,6,7,8};
        leftShift( array, 3);
        System.out.println( Arrays.toString( array));
    }
    
    public static void leftShift(int[] array, int n) {
        for (int shift = 0; shift < n; shift++) {
            int first = array[0];
            System.arraycopy( array, 1, array, 0, array.length - 1 );
            array[array.length - 1] = first;
        }
    }
    

    Output:

    [4, 5, 6, 7, 8, 1, 2, 3]
    

    Not too inefficient, as System.arraycopy() is highly optimized.

提交回复
热议问题