My external sort function works but it is way too slow. I think the bottleneck is the merge function. How can I make it faster. Is there a better merge function I can use for merging into a file using random access file objects and buffers?
private static void merge(String a, String b,
int l, int m, int r)throws FileNotFoundException, IOException
{
RandomAccessFile a1f = new RandomAccessFile(a,"rw");
RandomAccessFile b1f = new RandomAccessFile(b,"rw");
a1f.seek(l*4);
b1f.seek(l*4);
for(int i = l; i<m;i++){
a1f.seek(i*4);
b1f.seek(i*4);
int num = a1f.readInt();
b1f.writeInt(num);
}
for(int j=m; j<r; j++){
a1f.seek((m + r - j - 1)*4);
b1f.seek(j*4);
int num = a1f.readInt();
b1f.writeInt(num);
}
int i = l;
int j = r - 1;
//for (int i = l; i < m; i++) b[i] = a[i];
//for (int j = m; j < r; j++) b[j] = a[m + r - j - 1];
//if (b[j] < b[i]) a[k] = b[j--];
//else a[k] = b[i++];
for (int k = l; k < r; k++){
b1f.seek(j*4);
int b_j = b1f.readInt();
b1f.seek(i*4);
int b_i = b1f.readInt();
if(b_j<b_i){
b1f.seek((j--)*4);
a1f.seek(k*4);
a1f.writeInt(b1f.readInt());
}
else{
b1f.seek((i++)*4);
a1f.seek(k*4);
a1f.writeInt(b1f.readInt());
}
}
a1f.close();
b1f.close();
}