Split an array into two parts in Java
This post will discuss how to split an 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 solution
A naive solution is to create two new arrays and assign elements from the first half of the source array to the first array and elements from the second half of the source array to the second array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
import java.util.Arrays; class Main { // Method to split an array into two parts in Java public static void main(String[] args) { int[] inp = { 1, 2, 3, 4, 5 }; int n = inp.length; int[] a = new int[(n + 1)/2]; int[] b = new int[n - a.length]; for (int i = 0; i < n; i++) { if (i < a.length) { a[i] = inp[i]; } else { b[i - a.length] = inp[i]; } } System.out.println(Arrays.toString(a)); System.out.println(Arrays.toString(b)); } } |
Output:
[1, 2, 3]
[4, 5]
2. Using System.arraycopy() method
System.arraycopy() copies an array from a specified position in the specified source array to a specified position in the target array. We can make use of this method to split array, as shown below:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import java.util.Arrays; class Main { // Method to split an array into two parts in Java public static void main(String[] args) { int[] inp = { 1, 2, 3, 4, 5 }; int n = inp.length; int[] a = new int[(n + 1)/2]; int[] b = new int[n - a.length]; System.arraycopy(inp, 0, a, 0, a.length); System.arraycopy(inp, a.length, b, 0, b.length); System.out.println(Arrays.toString(a)); System.out.println(Arrays.toString(b)); } } |
Output:
[1, 2, 3]
[4, 5]
3. Using Arrays.copyOfRange() method
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.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.util.Arrays; class Main { // Method to split an array into two parts in Java public static void main(String[] args) { int[] inp = { 1, 2, 3, 4, 5 }; int n = inp.length; int[] a = Arrays.copyOfRange(inp, 0, (n + 1)/2); int[] b = Arrays.copyOfRange(inp, (n + 1)/2, n); System.out.println(Arrays.toString(a)); System.out.println(Arrays.toString(b)); } } |
Output:
[1, 2, 3]
[4, 5]
That’s all about splitting an array into two parts in Java.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)