Monday, 4 July 2011

Circular Right Shift Operation .

Here is the pearl for Circular Right Shift Operation in JAVA , given n shifts.


public int[] nRightShift(int[] data, int N){ // N specifies number of shifts
        int n = data.length;
        N = N %n;
               
        int[] data2 = new int[n];
       
        for(int i = n-1 ;i>=0 ;i--){
           data2[i] = data[(i-N+n)%n];   
        }
       
        return data2;
    }


Circular Left Shift Operation .

The following implementation in JAVA uses the magical modulo operator in order to find the index of the array location to copy.

 
public int[] nLeftShift( int[] data , int n){

        int N = data.length;   // Size of an Array
        n = n%N;                 // N shift operations means no shift operation.
       
        int[] data2 = new int[N];
       
        for(int i = 0; i< N ;i++){
            data2[i] = data[(i+n)%N];
        }
       
        return data2;
    }