Array: Shift elements of an array to the right

Q) Shift elements of an array to the right

Example:

Array:
1,2,3,4,5

Output:
5 1 2 3 4

public static void rightShiftElements (int [] array){
        int temp= array[array.length-1]; //store the last element in a variable

        for (int i= array.length-1; i>0; i--){ //run loop from the last element t the second element 
            array[i]= array[i-1]; //shift the element to the right
        }

        array[0]= temp; //store the last element in the first 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: