我的合并排序代码不起作用(Java)

时间:2015-05-02 09:53:09

标签: java algorithm mergesort

我刚刚写了这段代码已经尝试了很长时间,试图找出它为什么不打印排序列表。它正在运行并且没有错误,除了它不打印排序列表。能帮我找到什么错误吗?

public class Merging {
public static void main(String[] args) {
    int[] a = new int[10];

       populate(a);
        printA(a);



    a = merge_sort(a);
    printA(a);

}

public static int[] merge_sort(int[] B) {
    if (B.length <= 1) {
        return B;

    }

    int midpoint = B.length / 2;
    int[] left = new int[midpoint];
    int[] right= new int[B.length-midpoint];


    int[] result;


    for (int i = 0; i < midpoint; i++) {
        left[i] = B[i];

    }
    int x = 0;
    for (int j = midpoint; j < B.length; j++) {

        if (x < right.length) {


            right[x] = B[j];
            x++;
        }
    }

    left = merge_sort(left);
    right = merge_sort(right);

    result = merge(left, right);

    return result;

}

public static int[] merge(int[] left, int[] right) {

    int lengthResult = left.length + right.length;
    int[] result   = new int[lengthResult];
    int indexL = 0;
    int indexR = 0;
    int indexRes = 0;


    while (indexL < left.length || indexR < right.length) {

        if (indexL < left.length && indexR < right.length) {
            if (left[indexL] <= right[indexR]) {

                result[indexRes] = left[indexL];
                indexL++;
                indexRes++;


            } else {
                result[indexRes] = right[indexR];
                indexR++;
                indexRes++;

            }


        } else if (indexL < left.length) {

            result[indexRes] = left[indexL];
            indexL++;
            indexRes++;

        }


    }

    return result;

}

public static void printA(int[] B) {

    for (int i = 0; i < B.length; i++) {
        System.out.print(B[i] + " ");
    }
}

public static int[] populate(int[] B) {

    for (int i = 0; i < B.length; i++) {
        B[i] = (int) (Math.random() * 100);
    }
    return B;
}
}

1 个答案:

答案 0 :(得分:0)

想象你的循环中的情况,indexL < left.length == false但是indexR < right.length == true,你永远不会增加indexR而循环永远不会终止