MergSort算法java

时间:2015-11-11 19:32:36

标签: java mergesort pseudocode

所以我试图使用以下伪代码作为指南来实现一个mergsort算法:

Mergesort(A[0..n – 1])    
if n > 1
  copy A[0..[n / 2] – 1] to B[0..[n / 2] – 1]
  copy A[[n / 2]..n – 1] to C[0..[n / 2] – 1]
  Mergesort(B[0..[n / 2] – 1])
  Mergesort(C[0..[n / 2] – 1])
  Merge(B, C, A)
Merge(B[0..p – 1], C[0..q – 1], A[0..p + q – 1])
    i ← 0; j ← 0; k ← 0;
    while i < p and j < q do
       if B[i] <= C[j]
          A[k] ← B[i];  i ← i + 1
       else 
          A[k] ← C[j];  
          j ← j + 1
    k ← k + 1
    if i = p
       copy C[ j..q – 1] to A[k..p + q – 1]
    else 
       copy B[ i..p – 1] to A[k..p + q – 1]

我尝试尽可能地翻译它,然后我想出了以下代码:

public static void MergSort(int [] a){
    if (a.length > 1){
        int[] b = Arrays.copyOfRange(a, 0, a.length / 2);
        int[] c = Arrays.copyOfRange(a, a.length / 2, a.length);
        System.out.println("\nsub1: " + Arrays.toString(b));
        System.out.println("sub2: " + Arrays.toString(c));

        MergSort(b);
        MergSort(c);
        Merg(b, c, a);
    }
}
    public static void Merg(int [] b, int[] c, int[]a){
    int i = 0;
    int j = 0;
    int k = 0;
    int[] temp;
    int[] merg;

    while (i < b.length && j < c.length){

        if (b[i] <= c[j]){
            a[k] = b[i];  
            i++;
        }
        else{ 
            a[k] = c[j];  
            j++;
        }
        k++;
    }

    if (i == b.length){
        temp = Arrays.copyOfRange(c, j, c.length);

        merg = new int[a.length + temp.length];
        System.arraycopy(a, 0, merg, 0, a.length);
        System.arraycopy(temp, 0, merg, a.length, temp.length);

    }
    else{
        temp = Arrays.copyOfRange(b, i, b.length);

        merg = new int[a.length + temp.length];
        System.arraycopy(a, 0, merg, 0, a.length);
        System.arraycopy(temp, 0, merg, a.length, temp.length);
    }
}

但是当我使用以下数组2,5,100,69,1测试代码时,数组的结果为1,1,1,69,1。我认为我的逻辑错误发生在我的递归调用中但是我不确定。

0 个答案:

没有答案