Array shuffle Java

Array shuffle algorithm

Given an array of 2n integers in the following format a1 a2 a3 … an b1 b2 b3 … bn. Rearrange the array as follows a1 b1 a2 b2 a3 b3 … an bn taking into consideration the following restrictions:

1. Arrange the array in place i.e. do not use any additional array
2. Time complexity of the algorithm must be better than O(N2)

Solution

A brute force solution involves two nested loops to rotate the elements in the second half of the array to the left. The first loop runs n times to cover all elements in the second half of the array. The second loop rotates the elements to the left. Note that the start index in the second loop depends on which element we are rotating and the end index depends on how many positions we need to move to the left.

However this solution has a time complexity of O(n^2). A better solution of time complexity O(nlogn) can be achieved using Divide and Concur technique. Let us take an example

1. Start with the array: a1 a2 a3 a4 b1 b2 b3 b4
2. Split the array into two halves: a1 a2 a3 a4 : b1 b2 b3 b4
2. Exchange elements around the center: exchange a3 a4 with b1 b2 you get: a1 a2 b1 b2 a3 a4 b3 b4
3. Split a1 a2 b1 b2 into a1 a2 : b1 b2 then split a3 a4 b3 b4 into a3 a4 : b3 b4
4. Exchange elements around the center for each subarray you get: a1 b1 a2 b2 and a3 b3 a4 b4

Please note that this solution only handles the case when n = 2^i where i = 0, 1, 2, 3 etc. In our example n = 2^2 = 4 which makes it easy to recursively split the array into two halves. The basic idea behind swapping elements around the center before calling the recursive function is to produce a smaller size problems. A solution with linear time complexity may be achieved if the elements are of specific nature for example if you can calculate the new position of the element using the value of the element itself. This is nothing but a hashing technique.

Code

Here is a sample Java code to do that.

If you have questions or feedback, please use the comments section below. Thanks for visiting.

Add a Comment

Your email address will not be published. Required fields are marked *