我刚刚编写了这个合并排序的工作版本:
static int[] merge(int[] first, int[] second){
int totalsize = first.length + second.length;
int[] merged_array = new int[totalsize];
int i = 0, firstpointer = 0, secondpointer = 0;
while(i < totalsize){
if(firstpointer == first.length){
merged_array[i] = second[secondpointer];
++secondpointer;
}
else if(secondpointer == second.length){
merged_array[i] = first[firstpointer];
++firstpointer;
}
else if(first[firstpointer] < second[secondpointer]){
merged_array[i] = first[firstpointer];
++firstpointer;
}
else{
merged_array[i] = second[secondpointer];
++secondpointer;
}
++i;
}
return merged_array;
}
static int[] mergesort(int[] array){
if(array.length == 1){
return array;
}
else{
int length = array.length;
int[] first = Arrays.copyOfRange(array, 0, (int) length / 2);
int[] second = Arrays.copyOfRange(array, (int) length / 2, length);
return merge(mergesort(first), mergesort(second));
}
}
但是,如果您注意到,我使用 copyOfRange 函数创建一个新数组,该数组是父数组某个部分的副本。java中是否有比这更节省空间的合并排序实现?