Java Program to left rotate the Array

The following Java program rotates the array to d rotational integer. A left rotation operation on an array shifts each of the array’s elements  unit to the left. For example, if left rotations are performed on array [1,2,3,4,5], then the array would become [3,4,5,1,2].

The Code makes use of swapping using temp variable for circular rotation from left to right and shifting of the arrays from left to right. It uses two loops one goes from 0-length of the array and the other one goes from 0 to length-1. The code is pretty forward and it has been compiled and executed on netbeans.

Code:

import java.util.*;

class test{

    public static void main(String[] args) {
        
        int[] a = {1,2,3,4,5};
        int d = 4;
        int j=a[0],temp=0;
            for(int i=1;i<=d;i++){
                temp=a[0];

                 for(j=0;j<a.length-1;j++){
                     a[j]=a[j+1];                    
                 }
                a[a.length-1]=temp;

    }
        System.out.println(Arrays.toString(a));

    }
array left rotation
    }

OUTPUT:

 

Leave a Reply

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

%d bloggers like this: