## Block Swap Algorithm or Array Rotation in JavaIt is very interesting problem frequently asked in interviews of top IT companies like ## Array Rotation Example
int arr[] = {7, 9, 8, 0, 5, 1, 6, 4}, s = 8, d = 2
{9, 8, 0, 5, 1, 6, 4, 7}. Now, we rotate the array a second time, and we get the following. Let's see another example.
int arr[] = {6, 8, 7, 9, 0, 5, 1, 3, 2, 4}, s = 10, d = 5
{5, 1, 2, 3, 4, 6, 8, 7, 9, 0}, which is our answer. ## Block Swap AlgorithmIn this section, we have used block swap algorithm to rotate array. Observe the algorithm:
- If the size of A is greater than B, then divide A into two portions, A1 and A2, such that the size of A1 is equal to the size of A2. Swap the sub-arrays A1 and B. It changes the array from A1A2B to BA2A1.
- If the size of B > A, divide B into two parts, B1 and B2, in such a way that the size of B2 is the same as the size of B. Swap the subarrays A and B2. It changes the array from AB1B2 to B2B1A.
## Approach: Using RecursionThe following program uses the above-mentioned algorithm.
The input array: 7 9 8 0 5 1 6 4 The new array after rotating 2 times, we get 8 0 5 1 6 4 7 9 The input array: 6 8 7 9 0 5 1 3 2 4 The new array after rotating 5 times, we get 5 1 3 2 4 6 8 7 9 0 |

For Videos Join Our Youtube Channel: Join Now

- Send your Feedback to [email protected]