mergsort 打印出一个奇怪的结果

mergsort printing a strange result

我的合并排序有问题,当我打印出我的 sortedArray 时它只有 returns [ 0.0, 0.0.....] 我不确定我的排序代码是否有错误或在我的打印行中,或者是否与双打有关。我是我们的代码在下面发布。

通过调用 System.out.println(toString(sortedArray) 我得到了一个更加模糊的答案。

感谢您的帮助。

package mergesort;

import java.util.Arrays;
import java.util.Random;

public class mergesort {
    public static void main(String[] args) {
        double[] array = getIntArray();
        long before = System.nanoTime();
        double[] sortedArray= mergeSort(array);
        System.out.println("Sorting took  "+ (System.nanoTime() - before) +" nanoseconds ");
        System.out.println(toString(array) + "\n\n" + toString(sortedArray) + "\n main method completed in: " + (System.nanoTime() - before) + " nanoseconds.");

    }


    private static String toString(double[] array) {
        StringBuilder sb = new StringBuilder("[ ");
        double len = array.length;
        for(int i = 0; i < len - 1; i++) {
            sb.append(array[i] + ", ");
        }
        sb.append(array[(int) (len - 1)] + " ]");
        return sb.toString();
    }

    public static double[] mergeSort(double[] array) {

        if (array.length <= 1) {
            return array;
        }
        int half = array.length / 2;
        return merge(mergeSort(Arrays.copyOfRange(array, 0, half)),
                mergeSort(Arrays.copyOfRange(array, half, array.length)));
    }

    private static double[] merge(double[] ds, double[] ds2) {
        int len1 = ds.length, len2 = ds2.length;
        int totalLength = len1 + len2;
        double[] result = new double[totalLength];
        int counterForLeft =0,counterForRight=0,resultIndex=0;
        while(counterForLeft<len1 || counterForRight < len2){
            if(counterForLeft<len1 && counterForRight < len2){
                if(ds[counterForLeft]<= ds2[counterForRight]){
                    result[resultIndex++] =(int) ds[counterForLeft++];
                } else {
                    result[resultIndex++] =(int) ds2[counterForRight++];
                }

            }else if(counterForLeft<len1){
                result[resultIndex++] = (int) ds[counterForLeft++];

            }else if (counterForRight <len2){
                result[resultIndex++] =(int) ds2[counterForRight++];
            }
        }  
        return result;
    }

    private static double[] getIntArray() {
        double[] array = new double[10000];
        Random random = new Random();
        for(int i = 0;  i < 10000; i++) {
            array[i] = (random.nextDouble() * .99999);

        }

        return array;
    }
}

在合并方法中,当从输入数组之一复制到结果时,您转换为 int。例如:

result[resultIndex++] =(int) ds[counterForLeft++];

您所有的双打都在 [0...1) 范围内,因此将其中任何一个转换为 int 的结果为零。只要摆脱那些演员,你就会在合并结果中保留你的数字。

额外提示,调试小问题比调试大问题容易得多。对于任何大于 2 的大小,它都会失败,因此您应该一直使用大小 2 进行调试,而不是 10000。