Rotate Array in Java

Overview

In this article we will see how to rotate an array in Java. Let say we have an array of 8 elements: 1, 2, 3, 4, 5, 6, 7, 8. If we rotate this array from the second element, it will become 3, 4, 5, 6, 7, 8, 1, 2.

Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value

Code

Below is the code in Java to solve this problem.

package com.zia.array;

import java.util.Arrays;

public class RotateArray {

    public static void main(String[] args) {
        RotateArray rotateArray = new RotateArray();
        int arr[] = {1, 2, 3, 4, 5, 6, 7, 8};
        System.out.println("INPUT " + Arrays.toString(arr));
        rotateArray.leftRotate(arr, 2, 8);
        System.out.println("OUTPUT " + Arrays.toString(arr));
    }

    private void leftRotate(int[] arr, int d, int length) {
        for (int i = 0; i < d; i++) {
            leftRotateByOne(arr, length);
        }
    }

    private void leftRotateByOne(int[] arr, int length) {
        int temp = arr[0], i;
        for (i = 0; i < length - 1; i++) {
            arr[i] = arr[i+1];
        }
        arr[i] = temp;
    }
}

The time complexity for this solution is O(n)

Output

When you run the above code you will see the output as below:

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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: