Given the array nums consisting of 2n elements in the form [x1,x2,...,xn,y1,y2,...,yn], return the array in the form [x1,y1,x2,y2,...,xn,yn].
nums = [2,5,1,3,4,7], n = 3[2,3,5,4,1,7]x=nums[i], y=nums[i+n]The x-values are in the first half (indices 0..n-1) and y-values in the second half (n..2n-1). For each pair index i, we pick nums[i] and nums[i+n] and write them consecutively. The write position is always 2i and 2i+1.
You could split the array into two lists, then merge them. But a single loop with the right indexes does it directly.
The i-th pair is x at index i, and y at index i plus n. They go to positions 2 i, and 2 i plus 1.
The partner of index i in the second half is i plus n. Pair number i fills positions 2 i and 2 i plus 1.
Run the animation above on your own input, or watch the 1:17 video explanation of Shuffle the Array with a dry run and Java code.