Skip to content

1.4 Rotate Array to N Shift

Farrukh Ahmad edited this page Dec 15, 2015 · 1 revision

Rotate the given Array to n-times to right side

Given Array [1,2,3,4,5,6,7] and 3 times rotate will result [5, 6, 7, 1, 2, 3, 4]

public class ArrayRotate 
{    
public static void main(String args[]){
    int a[] = {1,2,3,4,5,6,7};
    System.out.println(Arrays.toString(rotate(a,3)));
}

static int[] rotate(int[] a, int k)
{
    int result[] = new int[a.length];
    
    for(int i=0; i<k; i++){
        result[i] = a[a.length-(k-i)];
    }
    
    int count =0;
    for(int j=k; j<a.length; j++)
    {
        result[j] = a[count++] ;
    }
    return result;
 }

}

Clone this wiki locally