Algorithm 1:
Public Static voidMain (string[] args) {int[] A =New int[]{1,2,3,4,5,6,7,8,9,10,11,12}; ShiftN2 (A,1); System.out.println (Arrays.tostring (a)); } Public Static voidShiftN2 (int[] A,intN) {n= n%a.length; Swaparray (A,0, N-1); Swaparray (A, n, A.length-1); Swaparray (A,0, A.length-1); } Private Static voidSwaparray (int[] A,intFromintRoo//[From, to] { inttemp; while(from<To ) {Temp=A[from]; A[from++] =A[to]; A[to--] =temp; } }
Algorithm 2:
Public Static voidMain (string[] args) {int[] A =New int[]{1,2,3,4,5,6,7,8,9,10,11,12}; for(inti = 0;i<a.length; ++i) {int[] Acopy =arrays.copyof (A, a.length); SHIFTN (acopy, i); System.out.println (arrays.tostring (acopy)); } } Public Static voidSHIFTN (int[] A,intN) {intL =a.length; N= n%l; if(n==0) return; intChanged = 0; inti = 0; while(changed<l) {intStart = 0-n + L +i; intfrom =i; intto =start; inttemp =A[to]; while(From! =start) {A[to]=A[from]; ++changed; to=From ; from= (from + N)%l; } A[to]=temp; ++i; ++changed; } }
Left Shift Array with O (l) time complexity and O (1) Space complexity