How to rotate the element of the array with a given input n, where ‘n’ is the number of rotation

  Rotate the element of the array with a given input, the following program able to rotate the array to the left side as a given number of 'n', n means how many elements will be rotated to the left side

Java Program Code :

   
 

/*;==========================================
; Title:  Rotate Array to the left  ( n - rotate )
; Author: codenaive littleboy8506@  <[email protected]> <[email protected]>
; Date:   29 Dec 2020
;==========================================*/

 class arrayOperation{
	 int data[]; // actual array data;
	 int length; // length of array data
	 public arrayOperation(String s){
		 String d[] =s.split(",");  // split the string into array 
		 length=d.length; // calculating the array length;
		 data = new int[length];	// set the length of array;
		 
		 // store the value of string data into int array .
		 for(int i=0;i<length;i++){
			data[i]=Integer.parseInt(d[i].trim());
		}
		 
	 }
	 public void  display(){
		 System.out.print("\t");
		 for(int i=0;i<length;i++){
			System.out.print(data[i]+" ");
			// display the data of array.
		 }
	 }
	 public void rotateLeft(int n){
		 
		 for(int i = 0; i<n;i++){
				int j, first_data;
				// store the first element to add at the end of array in one iteration.
				first_data=data[0];
				
				// if i=0 means the array will shift left by one value, similarly so on for i=0,1,2.
				for(j=0; j < length-1;j++){
						data[j]=data[j+1];
				}
				// append the value of first at the end of array.
				data[j]=first_data;
		 }
		 
	 }
	 
 }
 class Rotate {
	public static void main(String args[]){
		// here set the rotate vale to left.
		int n=3;  // rotation Value
		
		// create  object and pass the array value.
		arrayOperation obj = new arrayOperation("1,2,3,4,5,6,7,8");  // input here 
		
		// Before rotation of array.
		System.out.println("\nOriginal Array : ");
		obj.display();
		
		// After rotation of array.
		System.out.println("\nAfter Roate Left  : ");
		obj.rotateLeft(n);
		obj.display();
		
	}
	
 }

Output:

C:\Codenaive>javac Rotate.java

C:\Codenaive>java Rotate

Original Array :
        1 2 3 4 5 6 7 8
After Rotate Left  :
        4 5 6 7 8 1 2 3

Leave a Reply

Your email address will not be published. Required fields are marked *