Right Rotate an Array in Java - The Coding Shala

Home >> Java Programs >> Right Rotate an Array

 In this post, we will learn how to right rotate the elements of an array using the Java program.

Right Rotate an Array in Java

Write a Java program to Right Rotate the elements of an array by 1 position.

Example: 

Input: [1, 2, 3, 4, 5]
Output: [5, 1, 2, 3, 4]

Solution 1

We need to rotate the elements to the right by 1 position. We can store the last element in one variable and using for loop will shift all the elements to the right by 1 position.

syntax: arr[i] = arr[i-1]

After shifting all the elements move the last element[stored in variable] to the first index.

Java Program: 

/**
 * https://www.thecodingshala.com/
 */

import java.util.*;

public class Main {

    public static int[] rightRotate(int[] arr) {
        // last element will become first
        int last = arr[arr.length-1];
        for (int i = arr.length-1; i > 0; i--) {
            // shift the elements to right
            arr[i] = arr[i-1];
        }
        arr[0] = last;
        return arr;
    }

    public static void main(String[] args) {
        int[] arr = {1, 2, 3, 4, 5};
        System.out.println("Array before rotation: ");
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }

        System.out.println("\nArray after right rotation by 1: ");
        arr = rightRotate(arr);
        for (int i = 0; i < arr.length; i++) {
            System.out.print(arr[i] + " ");
        }
    }
}

Output: 

Array before rotation: 
1 2 3 4 5 
Array after right rotation by 1: 
5 1 2 3 4


Other Posts You May Like
Please leave a comment below if you like this post or found some errors, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

Add two numbers in Scala - The Coding Shala

New Year Chaos Solution - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala