user3701606
user3701606

Reputation: 5

Java split array into 2 other arrays, one with all numbers above a value and one with all below

I have a array with alot of numbers and I want to split it into 2 new arrays, one with all the numbers below a certain value and the other with the once above. The problem is that I dont know how many elements there will be in each array and I cant make larger arrays because it needs to be the exact size. Anyone know how to do this?

Upvotes: 0

Views: 276

Answers (2)

Mike Elofson
Mike Elofson

Reputation: 2037

If you want to use dynamic structures, such as a List implementation

public static void method1(Integer[] numbers, Integer barrier) {
    List<Integer> high = new ArrayList<Integer>();
    List<Integer> low = new ArrayList<Integer>();

    for (Integer i : numbers) {
        if (i > barrier) {
            high.add(i);
        } else {
            low.add(i);
        }
    }

    for (Integer i : high) {
        System.out.println("Higher: " + i);
    }

    for (Integer i : low) {
        System.out.println("Lower: " + i);
    }
}

If you want to use arrays, you still can but it will require more CPU cycles and memory

public static void method2(Integer[] numbers, Integer barrier) {
    int highNumbers = 0;
    int lowNumbers = 0;

    for (Integer i : numbers) {
        if (i > barrier) {
            highNumbers++;
        } else {
            lowNumbers++;
        }
    }

    Integer[] highArray = new Integer[highNumbers];
    Integer[] lowArray = new Integer[lowNumbers];
    Integer highArrayIndex = 0;
    Integer lowArrayIndex = 0;

    for (Integer i : numbers) {
        if (i > barrier) {
            highArray[highArrayIndex] = i;
            highArrayIndex++;
        } else {
            lowArray[lowArrayIndex] = i;
            lowArrayIndex++;
        }
    }

    for (Integer i : highArray) {
        System.out.println("Higher: " + i);
    }

    for (Integer i : lowArray) {
        System.out.println("Lower: " + i);
    }
}

I used a main method to test these:

public static void main(String[] args) throws Exception {

    Integer[] numbers = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
    Integer barrier = 5;

    method1(numbers, barrier);
    method2(numbers, barrier);

}

Upvotes: 0

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726499

There are two general ways of doing it:

  • Use dynamic containers to separate the numbers out. Once you are done, convert dynamic containers to arrays; or
  • Go through the array once to count the number of items in each array. Allocate the two arrays, then go through the input array one more time to populate the result arrays.

The first approach lets you work with inputs that can be iterated only once, but it requires more memory for temporary storage of data.

The second approach requires two passes through the input array, but it does not require additional temporary storage.

Upvotes: 2

Related Questions