How to divide an array into half 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.

Example

import java.util.Arrays;
import java.util.Scanner;

public class SplittingAnArray {
   public static void main(String args[]) {
      Scanner s =new Scanner(System.in);
      System.out.println("Enter the required size of the array ::");
      int size = s.nextInt();
      int [] myArray = new int[size];
      System.out.println("Enter elements of the array");
      for(int i=0; i< size; i++) {
         myArray[i] = s.nextInt();
      }
      System.out.println(Arrays.toString(myArray));
      int[] myArray1 = Arrays.copyOfRange(myArray, 0, myArray.length/2);
      int[] myArray2 = Arrays.copyOfRange(myArray, myArray.length/2, myArray.length);
      System.out.println("First half of the array:: "+Arrays.toString(myArray1));
      System.out.println("First second of the array:: "+Arrays.toString(myArray2));
   }
}

Output

Enter the required size of the array ::
6
Enter elements of the array
45
63
78
96
42
19
[45, 63, 78, 96, 42, 19]
First half of the array:: [45, 63, 78]
First second of the array:: [96, 42, 19]

Updated on: 19-Feb-2020

12K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements