Reputation: 5
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
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
Reputation: 726499
There are two general ways of doing it:
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