Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/unit-testing/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 是否有节省空间的mergesort实现?_Java_Mergesort_Space Complexity_Space Efficiency - Fatal编程技术网

Java 是否有节省空间的mergesort实现?

Java 是否有节省空间的mergesort实现?,java,mergesort,space-complexity,space-efficiency,Java,Mergesort,Space Complexity,Space Efficiency,我刚刚编写了这个mergesort的工作版本: 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){

我刚刚编写了这个mergesort的工作版本:

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));
    }

}
静态int[]合并(int[]第一,int[]第二){
int totalsize=first.length+second.length;
int[]合并的数组=新的int[totalsize];
int i=0,firstpointer=0,secondpointer=0;
而(i
但是,如果您注意到,我使用copyOfRange函数创建一个新数组,它是父数组某一部分的副本。java中是否有比这更节省空间的mergesort实现?

重复:

小结:是的,有一些节省内存的合并排序,但它们要么a)非常复杂,要么b)不节省时间:O(n^2 log n)

基本上,不用麻烦了。实际上,你节省的内存并不是那么多,如果你真的想,就用快速排序吧