Home » Java » Slice Array to left by K time in java

Slice Array to left by K time in java

public class SliceArray {

    public static void main(String[] args) {
        int[] givenArray = new int[]{1,5,2,1,6,7,5,8}; 
        int numOfTimes = 5;
        sliceArray(givenArray, numOfTimes);
    }
    
    private static void sliceArray(int A[], int K) {

        for (int a = 1; a < K + 1 ; a++) {
            // get the first element
            int last = A[A.length - 1];

            // Shift element to left by one
            for (int i = A.length - 1; i > 0; i--) {

                A[i] = A[i - 1];

            }

            // Fill first lement by last element
            A[0] = last;
        }

		// print new array
        for (int j = 0; j < A.length; j++) {
            System.out.print(A[j] + ",");
        }
    }
}
Please follow and like us:

Leave a Reply

Your email address will not be published. Required fields are marked *

*
*