I’m repeatedly merging 10000 sorted lists into a single long sorted list. Each list contains about 5000 doubles.
double[] result;// this is the single long sorted list
void merge(double[] x){
double[] newList=new double[x.length+result.length];
int i=0,j=0;
while(i<x.length && j<result.length){
insert the smaller one
increment i or j;
}
if(i<x.length){
add the rest
}
if(j<result.length){
add the rest
}
result=newList;
}
This method allocates a new array every time. As result[] grows, this is not efficient. Any advise?
You could handle it the same way ArrayList does and double the length of your array every time you need to reallocate and then only reallocate when you run out of space. Although you might have a fair amount of leftover space at the end, you would save processing time due to less allocations. Then just do an in-place merge with Result and X.