IMPLEMENT ROTATING AN ARRAY BY K POSITIONS IN JAVA

How to find rotating an Array by K positions.


1.   Rotating array is done in two parts trick. In the first part, we first reverse elements of
array first half and then second half.

2.   Then we reverse the whole array there by completing the whole rotation. 


import java.util.Scanner;
class ArrayRotation
{
public static void main(String[] args)
{
Scanner s= new Scanner(System.in);
int n=s.nextInt();
int arr[] =new int[n];
for(int i=0;i<n;i++)
{
arr[i]=s.nextInt();
}
System.out.println("enter positions to rotate");
int p=s.nextInt();
        ArrayRotate(arr,n,p);
        for(int i=0;i<n;i++)
        {
        System.out.println(arr[i]);
        }
     
}
public static void ArrayRotate(int[] a,int n,int k )
{
        reverseArray(a,0,k-1);
        reverseArray(a,k,n-1);
     
        reverseArray(a,0,n-1);
     
}
public static void reverseArray(int[] a, int start,int end)
{
for(int i=start,j=end;i<j;i++,j-- )
{
int temp=a[i];
a[i]=a[j];
a[j]=temp;

}

}

}

Comments

Popular posts from this blog

Problem Statement Of Real Estate Use Cases

Problem Statement Of Bank Marketing analysis

Hadoop