Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split array into two parts without for loop in java

Tags:

java

arrays

I have an array of size 300000 and i want it to split it into 2 equal parts. Is there any method that can be used here to achieve this goal?

Will it be faster than the for-loop operation or it will cause no effect on performance?

like image 700
Vinod Maurya Avatar asked Apr 20 '11 13:04

Vinod Maurya


People also ask

How do you split an array into two parts?

To divide an array into two, we need at least three array variables. We shall take an array with continuous numbers and then shall store the values of it into two different variables based on even and odd values.

Can you split an array in Java?

Using the copyOfRange() method you can copy an array within a range. This method accepts three parameters, an array that you want to copy, start and end indexes of the range. You split an array using this method by copying the array ranging from 0 to length/2 to one array and length/2 to length to other.

How do you cut an array in half?

splice() actually removes elements from the source array, the remaining elements in the array will be the elements for the right half. Math. floor() will round down to give the left side one less than the right side for odd lengths. You could use Math.


1 Answers

You can use System.arraycopy().

int[] source = new int[1000];  int[] part1 = new int[500]; int[] part2 = new int[500];  //              (src   , src-offset  , dest , offset, count) System.arraycopy(source, 0           , part1, 0     , part1.length); System.arraycopy(source, part1.length, part2, 0     , part2.length); 
like image 157
Martijn Courteaux Avatar answered Oct 01 '22 05:10

Martijn Courteaux