mergsort打印出一个奇怪的结果

时间:2016-07-19 19:59:50

标签: double mergesort println

我的合并排序存在问题,当我打印出sortedArray时,它只返回[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;
    }
}

1 个答案:

答案 0 :(得分:1)

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

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

所有双打都在[0 ... 1]范围内,因此将其中任何一个投射到int的结果为零。只是摆脱那些演员阵容,你将把你的数字保留在合并结果中。

作为补充提示,调试小问题要比大问题容易得多。任何大于2的大小都失败了,所以你应该调试大小为2而不是10000。