Array: Shifting elements of an array to the left

Q) Shifting elements of an array to the left

Example:

Array:
1,2,3,4,5

Output:
2 3 4 5 1

public static void leftShiftElements (int [] array){
        int temp =array[0]; //store the first element in a variable

        for (int i=0; i<array.length-1; i++){ //run the loop from 0 to length-2 because the last element will be replaced by temp
            array[i]= array[i+1]; //Shift the elements to the left
        }

        array[array.length-1]= temp; //shift the first element to the last position
}

Leave a Reply

PHP JS HTML CSS BASH PYTHON CODE

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: