Coders Packet

A Java program of Reversal method to right rotate an array by given number of elements

By Vimmi Singh

This is a Java code which uses reversal algorithm to rotate an array right. we input the size of array then we take a integer by which we have to rotate the array.

import java.util.*;
public class reversalRight {
//function to reverse an array
public static void reverse(int arr[],int si,int ei) {
while(si<ei) {
int c= arr[ei];
arr[ei]=arr[si];
arr[si]=c;
si++;
ei--;
}

}

public static void main(String[] args) {
// TODO Auto-generated method stub

Scanner sc=new Scanner(System.in);
int n=sc.nextInt();
int d=sc.nextInt();

int arr[]=new int[n];
for(int i=0;i<n;i++) {
arr[i]=sc.nextInt();
}

reverse(arr,0,d); //(reverse from index 0 to the number given)
reverse(arr,d+1,n-1); //(reversal of last elements)
reverse(arr,0,n-1); //(reversal of whole array)

for(int i=0;i<n;i++) {
System.out.println(" "+arr[i]);
}

}

}

First I have created a function which will reverse the array. Then in main method we will take size of the array(n) and the element by which we have to rotate the array (d) input from the user . Then we will take the array elements . Now we will reverse the front part of array( from 0 to d) then reverse the second part( that is from d+1 to the last element of array) then we will reverse the whole array it will give us the required result. Then finally we will print the array.

Download project

Reviews Report

Submitted by Vimmi Singh (VimmiSingh)

Download packets of source code on Coders Packet