Java Program For Array Rotation using temp array
After rotating d positions to the left, the first d elements become the last d elements of the array
- First store the elements from index d to N-1 into the temp array.
- Then store the first d elements of the original array into the temp array.
- Copy back the elements of the temp array into the original array
Illustration:
Suppose the give array is arr[] = [1, 2, 3, 4, 5, 6, 7], d = 2.
First Step:
=> Store the elements from 2nd index to the last.
=> temp[] = [3, 4, 5, 6, 7]Second Step:
=> Now store the first 2 elements into the temp[] array.
=> temp[] = [3, 4, 5, 6, 7, 1, 2]Third Steps:
=> Copy the elements of the temp[] array into the original array.
=> arr[] = temp[] So arr[] = [3, 4, 5, 6, 7, 1, 2]
Step-by-step approach:
- Initialize a temporary array(temp[n]) of length same as the original array
- Initialize an integer(k) to keep a track of the current index
- Store the elements from the position d to n-1 in the temporary array
- Now, store 0 to d-1 elements of the original array in the temporary array
- Lastly, copy back the temporary array to the original array
Below is the implementation of the above approach :
Java
/*package whatever //do not write package name here */ import java.io.*; class GFG { // Function to rotate array static void Rotate( int arr[], int d, int n) { // Storing rotated version of array int temp[] = new int [n]; // Keeping track of the current index // of temp[] int k = 0 ; // Storing the n - d elements of // array arr[] to the front of temp[] for ( int i = d; i < n; i++) { temp[k] = arr[i]; k++; } // Storing the first d elements of array arr[] // into temp for ( int i = 0 ; i < d; i++) { temp[k] = arr[i]; k++; } // Copying the elements of temp[] in arr[] // to get the final rotated array for ( int i = 0 ; i < n; i++) { arr[i] = temp[i]; } } // Function to print elements of array static void PrintTheArray( int arr[], int n) { for ( int i = 0 ; i < n; i++) { System.out.print(arr[i]+ " " ); } } public static void main (String[] args) { int arr[] = { 1 , 2 , 3 , 4 , 5 , 6 , 7 }; int N = arr.length; int d = 2 ; // Function calling Rotate(arr, d, N); PrintTheArray(arr, N); } } // This code is contributed by ishankhandelwals. |
3 4 5 6 7 1 2
Time complexity: O(N)
Auxiliary Space: O(N)
Java Program For Array Rotation
Write a Java Program for a given array of integers arr[] of size N and an integer, the task is to rotate the array elements to the left by d positions.
Examples:
Input:
arr[] = {1, 2, 3, 4, 5, 6, 7}, d = 2
Output: 3 4 5 6 7 1 2Input: arr[] = {3, 4, 5, 6, 7, 1, 2}, d=2
Output: 5 6 7 1 2 3 4