left rotation of array in java code example
Example 1: java code to right rotate an array
import java.util.*;
import java.lang.*;
import java.io.*;
class Codechef
{
public static void main (String[] args)
{
Scanner sc=new Scanner(System.in);
int arr[]= new int[10];
arr[0]=5;
arr[1]=34;
arr[2]=23;
arr[3]=6;
arr[4]=84;
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
System.out.println("");
for(int i=5;i>=2;i--)
{
arr[i+1]=arr[i];
}
arr[2]=15;
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
}
Example 2: array rotation program in java
static void rotLeft(int[] a, int d)
{
int [] n = new int[a.length];
for(int i = 0; i < a.length; i++)
{
int newlocation = (i+(a.length - d))% a.length;
n[newlocation] = a[i];
}
for(int i = 0; i < a.length; i++)
{
System.out.print(n[i]+ " ");
}
}
Example 3: rorate array
function rotateArray(A, K) {
if (!A.length) return A;
let index = -1;
while (++index < K) {
A.unshift(A.pop());
}
return A;
}
[
rotateArray([3, 8, 9, 7, 6], 3),
rotateArray([0, 0, 0], 1),
rotateArray([1, 2, 3, 4], 4),
rotateArray([], 4),
].join(' | ');