Split Array into Two Parts in Java

In this post, we will see how to split array into two parts in Java. If the array contains an odd number of items, the extra item should be part of the first array.


 

1. Naive

Naive solution would to create two new arrays and assign elements from first half of the source array to the first array and elements from second half of the source array to the second array.

Java

Download   Run Code

Output:

[1, 2, 3]
[4, 5]

 

2. System.arraycopy()

System.arraycopy() copies an array starting from specified position in the specified source array to specified position in the target array. We can make use of this method to split array as shown below:

Java

Download   Run Code

Output:

[1, 2, 3]
[4, 5]

 

3. Arrays.copyOfRange()

In both approaches discussed above, we manually allocate memory for both arrays. Java Collection Framework also provides one method copyOfRange() that copies the specified range of the source array into a new array and returns that array.

Java

Download   Run Code

Output:

[1, 2, 3]
[4, 5]

 
Thanks for reading.




Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz