How to rotate an array in java

0



Rotating an array left is one of the basic problem of the data structure. 

In this program we are given an array of N size also we are given a number D . So now we have to rotate the array leftwards by D positions .


Input: 

arr[] = {10, 20, 30, 40, 50, 60, 70}, d = 3

Output: 40 50 60 70 10 20 30


Input: 

arr[] = {11, 22, 33, 44, 55, 66}, d=2

Output: 33, 44, 55, 66, 11, 22





class HindiCodingCommunity {
public static void leftRot(int arr[], int d){
reverse(arr,0,d-1);
reverse(arr,d,arr.length-1);
reverse(arr,0,arr.length-1);
}
public static void reverse(int arr[],int low,int high){
while(low<high){
int temp=arr[low];
arr[low]=arr[high];
arr[high]=temp;
low++;
high--;
}
}
public static void printarr(int arr[]){
for(int i=0;i<arr.length;i++)
{
System.out.print(arr[i]+" ");
}
}
public static void main(String[] args) {
int[] arr={1,2,3,4,5,6};
leftRot(arr,2);
printarr(arr);
}
}


Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !