繁体   English   中英

递归mergesort仅对数组的一半排序

[英]Recursive mergesort only sorts half of an array

我试图实现一种递归合并排序算法,以对一个简单的整数数组进行排序,但是在数组的后半部分,我得到了一些奇怪的索引值。 上半部分似乎很好,考虑到它是递归实现的,这令人困惑。 随机整数数组是在我的main方法中初始化的。

public class MergeSort {

public static int Rounds = 1;
public static void MergeSort(Comparable[] ToSort, Comparable[] temp, int first, int last) {
    if(first < last) {
        int mid = (first + last) / 2;

        //Test Block
        System.out.print("For Round " + Rounds + ":\n");
        System.out.print("first = " + first + "   mid = " + mid + "   last = " + last + "\n");
        Rounds++;
        System.out.print("Array in Round " + (Rounds - 1) + " = {");
        for(int i = 0; i <= ToSort.length - 1; i++) {
            System.out.print(ToSort[i]);
            if(i < ToSort.length - 1)
                System.out.print(", ");
            else {
                System.out.print("}\n\n");
            }
        }

        MergeSort(ToSort, temp, first, mid);
        MergeSort(ToSort, temp, mid + 1, last);
        Merge(ToSort, temp, first, mid + 1, last);
    }

}

public static void Merge(Comparable[] ToSort, Comparable[] temp, int first, int mid, int last) {
    int beginHalf1 = first;
    int endHalf1 = mid - 1;
    int beginHalf2 = mid;
    int endHalf2 = last;
    int index = first;
    int Elements = (last - first) + 1;

    while(beginHalf1 <= endHalf1 && beginHalf2 <= endHalf2) {
        if(ToSort[beginHalf1].compareTo(ToSort[beginHalf2]) < 0) temp[index++] = ToSort[beginHalf1++];
        else temp[index++] = ToSort[beginHalf2++];
    }

    while(beginHalf1 <= endHalf1) temp[index++] = ToSort[beginHalf1++];
    while(beginHalf2 <= endHalf2) temp[index++] = ToSort[beginHalf2++];
    for(int i = 0; i < Elements; i++, last--) ToSort[last] = temp[last];

}

}

这将产生以下输出:

未排序阵列= {15,9,12,19,49,43,57,70,78,87}对于回合1:第一= 0中= 4最后= 9第一回中的数组= {15,9,12,19 ,49,43,57,70,78,87}

对于第2轮:第一个= 0中间= 2最后一个= 4第2轮中的数组= {15、9、12、19、49、43、57、70、78、87}

对于第3轮:第3场中的第一个= 0中= 1最后一个= 2数组= {15,9,12,12,19,49,43,57,70,78,87}

对于第4轮:第一个= 0中= 0最后= 1第4轮中的数组= {15,9,12,19,49,43,57,70,78,87}

对于第5轮:第= 3个中= 3个最后= 4个第5轮中的数组= {9,12,15,19,49,43,57,70,78,87}

对于第6轮:第一个= 5中= 7最后= 9第6轮中的数组= {9,12,15,19,49,43,57,70,78,87}

对于第7轮:第一个= 5中= 6最后= 7第7轮中的数组= {9,12,15,19,49,43,57,70,78,87}

对于第8轮:第一个= 5中= 5最后= 6第8轮中的数组= {9,12,15,19,49,43,57,70,78,87}

对于第9轮:第一个= 8中= 8最后= 9第9轮中的数组= {9,12,15,19,49,43,57,70,78,87}

您的实现没有错误。 如果在应用MergeSort方法之后打印数组,则将对其进行排序:

Comparable[] a = new Comparable[]{15, 9, 12, 19, 49, 43, 57, 70, 78, 87};
Comparable[] b = new Comparable[a.length];
MergeSort.MergeSort(a, b, 0, a.length - 1);

for (int i = 0; i <= a.length - 1; i++) {
    System.out.print(a[i]);
    if (i < a.length - 1)
        System.out.print(", ");
    else {
        System.out.print("}\n\n");
    }
}

将打印9, 12, 15, 19, 43, 49, 57, 70, 78, 87}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM